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?
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)
[[[...]]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With