+ 4

Python - append a list to the same list

Hi, I don't understand the output of this code: a = [1,2] a.append(a) print (a) print (a[2][2][2]) print (a != a[2][2][2]) Output: [1,2, [...]] [1,2, [...]] False 1) why a is [1,2,[...]] and not [1,2,1,2]? What does [...] mean? 2) why does a[2][2][2] result in [1,2,[...]]? 3) why is a the same as a[2][2][2]? Please help.

23rd Jun 2019, 7:31 AM
Marek Kluczewski
Marek Kluczewski - avatar
4 Respostas
+ 13
By appending a list to itself, you create a self-referencing list. This is denoted by the ellipsis ([...]). It's like a recursive function (without a break condition). list1 = [1, 2, 3] list1.append(list1) print(list1) # [1, 2, 3, [...]] When you "zoom in" on the self-referencial fourth list item, you get the same list again: print(list1[3]) # [1, 2, 3, [...]] And this list slice's fourth element is the same as the original list again: print(list1[3][3]) # [1, 2, 3, [...]] You could do this forever and would always get the same result. So this is a lot like one of these fractal images. In your example, it's [1,2,[...]] and not [1,2,1,2] because you append a reference to itself to the same list again. Instead of saying a = [1,2] a.append([1, 2]), you say a = [1,2] a.append(a) which leads to the above-mentioned "recursive" effect. Another way to actually append [1, 2] to the list would be a = [1,2] a.append(a[:]) print(a) # [1, 2, [1, 2]]
23rd Jun 2019, 8:23 AM
Anna
Anna - avatar
+ 10
In general, appending a list to another list means that you have a list item as one of your elements of your list. For example: a = [1,2] a.append([3,4]) print(a) # [1,2,[3,4]] In your example, a is appended to itself, so now a is an element within itself. So when you have a = [1,2] a.append(a) you've basically made a[2] the same as a. So if you were to write the whole thing out, you would get a = [1,2,[1,2,[1,2,[1,2,[...]]]]] That's what [...] means - you have created a bottomless rabbit hole. So a[2] == a, a[2][2] == a, a[2][2][2] == a and so on.
23rd Jun 2019, 8:24 AM
Russ
Russ - avatar
+ 10
To add the elements of a list to itself you can also use extend() instead of append: a = [1,2] a.extend(a) print (a) # putput: [1, 2, 1, 2]
23rd Jun 2019, 9:39 AM
Lothar
Lothar - avatar
+ 3
Hi there. I don't really understand the crazy world of append, but if you don't want a multidimensional list, then you shouldn't use append, because it pushes only 1 value at the end of it. You might want to use the + (or *) operator. Example: a = [1, 2] a = a + a print(a) # [1, 2, 1, 2]
23rd Jun 2019, 7:43 AM
Airree
Airree - avatar