cyclic data structures

John Salerno johnjsal at NOSPAMgmail.com
Mon Feb 13 15:44:29 EST 2006


I'm having some slight trouble understanding exactly why this creates an 
infinite loop:

L = [1, 2]
L.append(L)

In a highly abstract way, I understand it. But if I were asked to write 
down what I think L is after the second line executes, I would write:

[1, 2, [1, 2]]

But the correct answer seems to be:

[1, 2, [1, 2 [1, 2 [ .......

I guess what confuses me is that there doesn't seem to be anything 
inherent in L itself that would cause this repeat. If you add L to L, 
why don't you just get two Ls? Where does the cycle begin? Is this just 
a quirk that comes with having a variable include a reference to the 
same object the variable references?



More information about the Python-list mailing list