Python: “a.append(a)” evaluates to a strange infinite recursive list?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Python: “a.append(a)” evaluates to a strange infinite recursive list??

a = [1,2] a.append(a) print(a == a[2][2][2]) # True Here print(a) shows [1, 2, [...]]. So “a” is a list with an embedded list “a” with an embedded list “a” ...and so on? A pointer that references to itself? How does it work exactly?

11th Mar 2020, 9:09 AM
Prof. Dr. Zoltán Vass
2 Answers
+ 5
a.append(a) will create some kind of loop where the third element will be the list itself... Basically it is a = [1,2, a] Where a again is equal to a = [1,2,a] ( a = [1,2,[1,2,a]] if we expand it once) So it can be represented as a = [1,2, [1,2,[1,2,...]]] So it is infinite as the a[2] = a everytime and the print(a == a[2][2][2]) is true because a = [1, 2, a] a[2] == a a[2] == [1,2,a] a[2][2] == a . . . a[2][2][2][2] == a . . . I hope you understand
11th Mar 2020, 9:40 AM
Utkarsh Sharma
Utkarsh Sharma - avatar
+ 2
If you imagine a referencing as an instruction to look up a certain data item in memory, you could rephrase a list lookup as: 'Please go to the address stored in slot i and give me what's there.' So if the address of the list itself is stored in there, it will look up itself. And if you write some code with a loop around it, trying to get to the bottom of it, it is possible to get a recursion error. https://code.sololearn.com/c8FJrflBhwp6/?ref=app
11th Mar 2020, 9:23 AM
HonFu
HonFu - avatar