How does Python primarily manage memory for objects?
Short answer
CPython uses automatic reference counting as its primary memory management mechanism: every object tracks how many references point to it, and when that count drops to zero, the memory is immediately deallocated.
Advertisement
AModel answer
CPython uses automatic reference counting as its primary memory management mechanism: every object tracks how many references point to it, and when that count drops to zero, the memory is immediately deallocated. A supplementary cyclic garbage collector handles reference cycles that reference counting alone cannot free.
import sys
a = [1, 2, 3]
print(sys.getrefcount(a)) # includes the temporary ref from getrefcount's own argument
b = a
print(sys.getrefcount(a)) # increased by oneReal-world example
Understanding refcounting explains why a large object is freed the instant its last variable goes out of scope or is reassigned, without waiting for a garbage collection cycle.
Likely follow-ups
- What increases and decreases an object's reference count?
- Why do reference cycles need a separate collector?
Related topics