+ 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?
7 ответов
+ 4
List2=list1[:]
Create a copy of list1
+ 4
+ 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
+ 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.
+ 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)
0
Ka♏aL💯