I came across an issue in python appending to a list. The code I implemented was:
a=[1,2]
b=[3,4]
a.append(b)
b.append(5)
print a
print b
My understanding of python append was that the expected output of this code would be:
Expected Output
a=[1,2,[3,4]]
b=[3,4,5]
But the actual output is something different. Actual Output
a=[1,2,[3,4,5]]
b=[3,4,5]
I just want to know why this happened.
Since I appended the list b
to a
, before appending 5
to b
, list a
should have [1,2,[3,4]]
Python names are references, and appending to a list appends a reference to the same object.
In other words, you did not append a copy of the b
list. The a
list and the name b
share a reference to one and the same object:
>>> a = [1, 2]
>>> b = [3, 4]
>>> a.append(b)
>>> a[-1] is b # is tests if two references point to the same object
True
>>> id(a[-1]), id(b) # id produces a unique number per object
(4595716320, 4595716320)
If you expected to add a copy of the b
list to a
, do so explicitly:
a.append(b[:])
or
a.append(list(b))
See How to clone or copy a list?
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