What is Python's memory management and garbage collection?
Why Interviewers Ask This
This is a differentiating question used for senior and lead roles. Interviewers want to see if you can explain not just what happens, but why — and what the trade-offs are in different approaches.
Answer
CPython uses reference counting as the primary memory management strategy — every object has a reference count incremented when referenced and decremented when dereferenced. When the count reaches zero, memory is freed immediately. This handles most cases efficiently with no GC pause. However, reference counting fails for circular references (A → B → A). CPython's supplementary cycle garbage collector (the gc module) periodically identifies and frees circular reference cycles. GC is organized into three generations: gen0 (young objects, collected frequently), gen1, gen2 (old objects, collected rarely). Disable GC for performance-critical code (if no circular references): gc.disable(). Profile memory with tracemalloc. Tools: objgraph (visualize object references), memory_profiler (line-by-line memory usage). Python 3.12 improved GC with the new low-impact incremental collector.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Python answers easy to follow.
Previous
What is Python's @dataclass vs namedtuple vs attrs?
Next
What is Python's __dunder__ (magic) methods?