Python: assigning lists | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Python: assigning lists

By challenges exercises, it seems to me, when you equals two lists: list2 = list1 sometimes list2 references list1, sometimes it's a copy of its own. Is there a general rule to distinguish two cases?

14th Sep 2019, 1:35 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
7 Answers
+ 4
List2=list1[:] Create a copy of list1
14th Sep 2019, 3:49 PM
guillem ardanuy
guillem ardanuy - avatar
14th Sep 2019, 5:04 PM
Seb TheS
Seb TheS - avatar
15th Sep 2019, 9:57 AM
Manoj
Manoj - avatar
+ 3
Ha - interesting to know! Thanks for making that one! I think, adding deepcopy is a bit unfair because we have simple objects here. Its strong points might come out when you have multi-dimensional lists or something
14th Sep 2019, 5:07 PM
HonFu
HonFu - avatar
+ 2
I want to point out that in Python when you write varB = varA, it's *always* a reference to the same object - like a second name sticker. It's just with lists (and other mutable types), that it can lead to issues. Make a few experiments with different types and use the id function to confirm that it's actually always that very object.
14th Sep 2019, 2:39 PM
HonFu
HonFu - avatar
+ 1
You can use: list2 = list1.copy() to make sure that changes on the lists don't affect each other, but if list1 contained lists, list1.copy() doesn't make copies of the inner lists, but uses the original inner lists instead. This can be fixed with copy.deepcopy: import copy list2 = copy.deepcopy(list1)
14th Sep 2019, 1:47 PM
Seb TheS
Seb TheS - avatar
0
Ka♏aL💯
15th Sep 2019, 10:17 PM
Esteves Fraser Sgt
Esteves Fraser Sgt - avatar