Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if you append a list to itself?

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?

like image 925
Aashish P Avatar asked Feb 12 '23 16:02

Aashish P


1 Answers

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)
[[[...]]]
like image 145
Martijn Pieters Avatar answered Feb 15 '23 10:02

Martijn Pieters