+ 2

Why appears few lists after .append?

Here is the python code: a, b = [], [] for x in range(4): a.append(x) b.append(a) print(b) Output is: [[0]] [[0, 1], [0, 1]] [[0, 1, 2], [0, 1, 2], [0, 1, 2]] [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]] I suppose the final output like [0, [0, 1], [0, 1, 2], [0, 1, 2, 3]] and don’t understand why there are few equal lists. Could anyone explain, please!

16th Feb 2019, 2:08 PM
Anna Starikova
Anna Starikova - avatar
6 Respuestas
+ 8
If you append an object to a list, you append no copy but (a reference to) that actual object. So if you first append a to another list and then append something to a, the a in the list changes, too: because it's the very same a! And if you append a many times, the name (reference to) a will be in it many times; this just means that whenever your list finds an a, it will look up that very same object a again and again. If you don't want this behaviour, you have to append an actual copy of a instead of a: b.append(a[:])
16th Feb 2019, 2:32 PM
HonFu
HonFu - avatar
+ 13
It's happening because the variable "a" is a reference to a list, so each append basically appends the reference to "a" which is constantly changing edit: HonFu beat me to it 😅 and explained it more thoroughly
16th Feb 2019, 2:35 PM
Burey
Burey - avatar
+ 3
I’ll try a slightly different explanation to that of the other commenters thus far, just on case you find it helpful. Your empty list b has the list a appended to it 4 times. This means that your list b, at the end of the code, is [a,a,a,a]. Since a, at the end, is [0,1,2,3], that is why it ends up as it does. In order to get the result you were expecting, simply change line 4 to b.append(list(a)). This appends the list that a is at that moment, rather than a itself. Hope that helps.
16th Feb 2019, 3:23 PM
Russ
Russ - avatar
+ 3
HonFu thank you very match. Your explanation very useful and clearly. ⚡Prometheus ⚡ , Burey , Russ also many thank’s
16th Feb 2019, 3:50 PM
Anna Starikova
Anna Starikova - avatar
+ 2
😎😂
16th Feb 2019, 2:39 PM
HonFu
HonFu - avatar
+ 1
You're appending the same reference again and again. To solve this, do: b=[list(range(0,n)) for n in range(4)]
16th Feb 2019, 3:06 PM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar