What happens if you add the list to yourself?

What happens if I try to add a list to myself?

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

What does it mean? Does a some_listrecursive list return ? What will happen with reference to the counter some_list? How will the garbage collector relate to this? When some_listwill this be garbage collected?

+4
source share
1 answer

Yes, you have created a circular link; the list object is referenced by itself. This means that the link counter is incremented by 1 additional link.

The Python garbage collector will handle this case; if nothing else refers to the list object, the garbage collector process is responsible for breaking this 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)
[[[...]]]
+7
source

Source: https://habr.com/ru/post/1545586/


All Articles