Home > Enterprise >  Do I really need to list.copy() a list before append?
Do I really need to list.copy() a list before append?

Time:09-27

I have two lists,

list1 = [91, 95, 97, 99]
list2 = [92, 93, 96, 98]

Can I just use list2.extend(list1) if I want to merge them and arrange them with list2.sort()?

Or do I need to make a copy of it before extend?

list3 = list1.copy()
list3.extend(list2)

And why is my list not sorted if I do

list3 = []
list3.append(list1   list2)
list3.sort()
print(list3)

CodePudding user response:

It depends on what you need to do. If you don't intend to use the original content of list2 (before merging and sorting) elsewhere in your program, then you don't need to make a copy.

CodePudding user response:

First things first, you need to keep in mind which functions return a list and which ones modify/mutate the list the function is called on. Here is a summary:

  • extend, append and sort mutates a list, but sorted returns a new list.

So yes you can extend one list with another and then sort it as you have done. You don't need to make a copy (unless you actually need to for some reason).

does the same thing as extend when used with lists. Unfortunately, list3.append(list1 list2) doesn't do what you think it does, append is for adding individual items to the end of a list, you need to use or extend if you want to add one list to another as you had before, e.g. new_list = list1 list2 list3. Then you can sort and print it.

CodePudding user response:

In answer to your last question:

list1 = [91, 95, 97, 99]
list2 = [92, 93, 96, 98]
list3 = []
list3.append(list1   list2)

This appends a list inside a list. If you print(list3) you get [[91, 95, 97, 99, 92, 93, 96, 98]]

The .sort() method attempts to sort the outer list, of which there is only 1 element, which can't be sorted any further. To sort that list you would need to do, list3[0].sort() Now printing list3 gives you, 'print(list3)`

[[91, 92, 93, 95, 96, 97, 98, 99]]

  • Related