l = [1, 2]
l.append(l)
>>>l
[1, 2, [...]] #l is an infinite list
Why does this create an infinite list instead of creating:
l = [1, 2]
l.append(l)
>>>l
[1, 2, [1, 2]]
l = [1, 2]
l.append(l)
>>>l
[1, 2, [...]] #l is an infinite list
Why does this create an infinite list instead of creating:
l = [1, 2]
l.append(l)
>>>l
[1, 2, [1, 2]]
When you do:
l.append(l)
a reference to list l
is appended to list l
:
>>> l = [1, 2]
>>> l.append(l)
>>> l is l[2]
True
>>>
In other words, you put the list inside itself. This creates an infinite reference cycle which is represented by [...]
.
To do what you want, you need to append a copy of 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
>>>
Easy, because each object will have a reference to itself in the third element. To achieve [1, 2, [1, 2]]
then use a copy of the list.
l.append(l[:])