Skip to content Skip to sidebar Skip to footer

Why Does Appending A List By Itself Create An Infinite List

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

Solution 1:

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[:])

Post a Comment for "Why Does Appending A List By Itself Create An Infinite List"