So this just blew my mind. I am working on a python code where I create a list, append it to a master list and clear the first list to add some more elements to it. When I clear the first list, even the master list gets cleared. I worked on a lot of list appends and clears but never observed this.
list1 = []
list2 = []
list1 = [1,2,3]
list2.append(list1)
list1
[1, 2, 3]
list2
[[1, 2, 3]]
del list1[:]
list1
[]
list2
[[]]
I know this happens with appending dictionaries but I did not know how to deal with lists. Can some one please elaborate?
I am using Python2.7
Passing a list
to a method like append
is just passing a reference to the same list
referred to by list1
, so that's what gets appended to list2
. They're still the same list
, just referenced from two different places.
If you want to cut the tie between them, either:
list1
, not list1
itself, e.g. list2.append(list1[:])
, orlist1
with a fresh list
after append
ing instead of clearing in place, changing del list1[:]
to list1 = []
Note: It's a little unclear, but if you want the contents of list1
to be added to list2
(so list2
should become [1, 2, 3]
not [[1, 2, 3]]
with the values in the nested list
), you'd want to call list2.extend(list1)
, not append
, and in that case, no shallow copies are needed; the values from list1
at that time would be individually append
ed, and no further tie would exist between list1
and list2
(since the values are immutable int
s; if they were mutable, say, nested list
s, dict
s, etc., you'd need to copy them to completely sever the tie, e.g. with copy.deepcopy
for complex nested structure).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With