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)
[[[...]]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.