0
What is the difference between assigning items to a list one by one vs all at once?
5 Answers
+ 7
Oh, I'm so sorry! I didn't check your code so carefully before!
Actually, when we do list1 = list2, the elements in list2 is not copied over to list1. Basically, we are just giving list2 another name. They remain the same lists. Any changes to list1 will be reflected in list2, and vice versa.
If you want to get copies of the elements, you can do
list1 = list2[:]
[But even that works best if the elements in list2 are immutable (like numbers, strings, tuples, etc). If list2 contains mutable objects like another list inside it, the safest method is using deepcopy() from the copy module. https://docs.python.org/3.7/library/copy.html]
+ 8
Clearer examples here
https://code.sololearn.com/cXcm6er1b4a1
+ 4
Doing it all at once is faster. But sometimes we don't have a choice. Say you want to make a list where the first number is 2, and every other number is the square of the previous one. So like
2, 4, 16, 256, ...
Only when you know the number in a certain position that you can add the next one. So we can't create the list all at once; we append the elements one at a time.
+ 1
In this case, seems obvious :D
My problem is that if I have list1 = list 2 and after that I made some changes to list1, the changes also occurs in list2. On the other hand, if the items in list1 are declared as list1.append(list2[x]), then list1 and list2 are considered different lists. But I think this has something to do with how the lists are stored in memory
+ 1
Nice. It works with list[:] since the list has only number as items.
Thank you!