+ 3

Appending Lists, why is the output the way it is?

Consider this code: a, b = [0], [1] a.append(b) b.append(a) print(a) print(b) # I expected an output like [0, [1]] # [1, [0, [1]]] # but it rather becomes an infinite list, can # someone explain please?

19th Mar 2018, 10:23 AM
Khushal Sahni
Khushal Sahni - avatar
3 odpowiedzi
+ 11
🔹Because you've appended a pointer to that list, so when b changes the pointer sees the change. Same thing when a changes. In your case result become infinite list... 👉 a.append(b) ⤵️ a is now [original_list_object_a,original_list_object_b]. So, when you change b, you change what a refers to. ... 🔹If you want to create a copy and therefore point to a different object, you can use next: a, b = [0], [1] a.append(b[:]) b.append(a[:]) print(a) print(b)
19th Mar 2018, 10:43 AM
LukArToDo
LukArToDo - avatar
+ 8
@Khushal Exactly! 👍 You're welcome 😉
19th Mar 2018, 10:52 AM
LukArToDo
LukArToDo - avatar
+ 2
Oh I think i get it somewhat, when we append b to a we are not appending the value of b but actually appending it's "address's value" so whenever b changes a changes too and this how it becomes an Infinite list. Thanks Lukar ToDo ! :)
19th Mar 2018, 10:51 AM
Khushal Sahni
Khushal Sahni - avatar