What is the difference between assigning items to a list one by one vs all at once? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What is the difference between assigning items to a list one by one vs all at once?

https://code.sololearn.com/ckiu5uRxkW9s/?ref=app

5th Nov 2018, 12:35 PM
Madalin Nicolaescu
Madalin Nicolaescu - avatar
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]
5th Nov 2018, 1:29 PM
Kishalaya Saha
Kishalaya Saha - avatar
5th Nov 2018, 2:35 PM
Flandre Scarlet
Flandre Scarlet - avatar
+ 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.
5th Nov 2018, 12:45 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 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
5th Nov 2018, 1:15 PM
Madalin Nicolaescu
Madalin Nicolaescu - avatar
+ 1
Nice. It works with list[:] since the list has only number as items. Thank you!
5th Nov 2018, 2:07 PM
Madalin Nicolaescu
Madalin Nicolaescu - avatar