4

What will happen if I try to append a list to itself?

# Let's say empty list is created.
some_list = []
# Now, append it with self
some_list.append(some_list)
# Output shows [[...]] on iPython console.

What does this mean? Does some_list become recursive list or something ? What will happen to reference count of some_list? How garbage collector will treat this? When this some_list will be garbage collected?

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
Aashish P
  • 1,894
  • 5
  • 22
  • 36

1 Answers1

8

Yes, you created a circular reference; the list object references itself. This means that the reference count goes up by 1 extra reference.

The Python garbage collector will handle this case; if nothing else references the list object anymore the garbage collector process is responsible for breaking that circle:

>>> import gc
>>> some_list = []
>>> gc.get_referents(some_list)
[]
>>> some_list.append(some_list)
>>> some_list[0] is some_list
True
>>> gc.get_referents(some_list)
[[[...]]]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343