Problem Statement
Explain how Python memory management works: reference counting, cycles, and the garbage collector.
Explanation
CPython primarily uses reference counting. Each object tracks how many references point to it. When the count drops to zero, the object is freed immediately. This makes most reclamation prompt and predictable.
Reference cycles cannot be collected by counting alone, so a cyclic garbage collector runs occasionally to find groups of objects that reference each other but are otherwise unreachable. You can tune collection thresholds with the gc module, but most apps do not need manual tweaks.
Be careful with objects that define finalizers; cycles containing them may not be collected automatically. Breaking cycles with weak references or context managers keeps memory healthy.
Code Solution
SolutionRead Only
import gc print(gc.get_threshold()) # gc.collect() can force a cycle collection
