Python · Memory & Internals

How does Python manage memory?

Hardmemorygcrefcountcpython

Interview question

How does Python (CPython) manage memory?

How to answer

The short answer

CPython uses a mix of reference counting and a cyclic garbage collector.

  1. 1Reference counting: Each object tracks how many references point to it. When the count hits zero, the object is deallocated immediately.
  2. 2Cyclic GC: Reference counting alone cannot free reference cycles (a.x = b; b.y = a). The gc module periodically finds and collects unreachable cycles.
  3. 3Allocators: Small objects often come from pymalloc arenas; larger allocations go to the system allocator. Free lists may reuse some object types (e.g. small ints historically, some containers).
  4. 4Interning / caching: Some immutable values are shared (see interned strings / small ints).
Python
import gc
import sys

a = []
b = []
a.append(b)
b.append(a)
del a, b
collected = gc.collect()
print("cycles collected:", collected)

x = "lakebench"
print(sys.getrefcount(x))  # includes temporary ref from the call

Implications

  • Most objects die promptly when references disappear.
  • Long-lived caches and cycles can retain memory until GC runs.
  • __del__ finalizers complicate cycle collection; avoid relying on them for critical resource cleanup (prefer ).

Other Python implementations (PyPy, Jython) may use different GC strategies.

Lock it in with a real drill

You remember an answer longer once you have used it. Try a hands-on problem on this concept.

Open related drill