Why adding a list in itself creates an endless list

l = [1, 2]
l.append(l)
>>>l
[1, 2, [...]] #l is an infinite list

Why does this create an endless list instead of creating:

l = [1, 2]
l.append(l)
>>>l
[1, 2, [1, 2]]
+4
source share
2 answers

When you do:

l.append(l)

The link to the list is ladded to the list l:

>>> l = [1, 2]
>>> l.append(l)
>>> l is l[2]
True
>>>

In other words, you put the list inside yourself. This creates an endless reference cycle that is presented [...].


To do what you want, you need to add a copy of the list l:

>>> l = [1, 2]
>>> l.append(l[:])  # Could also do 'l.append(list(l))' or 'l.append(l.copy())'
>>> l
[1, 2, [1, 2]]
>>> l is l[2]
False
>>>
+8
source

Easy, because each object will have a link to itself in the third element. Use a [1, 2, [1, 2]]copy of the list to achieve .

l.append(l[:])
+2
source

All Articles