Sobes.tech
Middle

How does garbage collector work in Python? If a memory cell references another memory cell — will GC delete both references or do nothing?

sobes.tech AI

Answer from AI

In Python, the garbage collector (GC) works based on reference counting and additionally uses a cycle detection algorithm.

  • Each object maintains a reference count — the number of active references to it.
  • When the count reaches 0, the object is immediately deleted.
  • However, if objects reference each other in a cycle but are not accessible from the program, their reference counts do not reach 0.
  • For such cases, Python runs a cyclic garbage collector that searches for and deletes object cycles that are inaccessible from the code.

If a memory cell (object) references another, the GC will not delete both if there are still external references to them. However, if both are linked in a cycle and inaccessible, the cyclic GC will delete the entire cycle.

Example:

import gc

a = []
b = [a]
a.append(b)

# a and b reference each other, creating a cycle
# If external references are removed:
del a
# b still exists

del b

# Now the cycle is inaccessible, GC can collect it
gc.collect()
How does garbage collector work in Python? If a… - sobes.tech