Memory Management & GCAdvanced
1Question 1 of 1
pythonHow does Memory Management and Reference Counting work in Python?
Explanation & Concept
CPython manages memory primarily through **Reference Counting**: every object tracks how many variables refer to it. When the count drops to 0, memory is immediately deallocated.
To handle **Reference Cycles** (e.g. Object A references B, and B references A), CPython runs a generational cyclic garbage collector that tracks container objects.
Code Example
python
import sys
data = ["hello", "world"]
print(sys.getrefcount(data)) # Reference count (includes getrefcount argument)
alias = data
print(sys.getrefcount(data)) # Incremented by 1
del alias # Decremented by 1How It Works & Key Takeaways
Avoid creating circular references in complex graph objects, or use `weakref` to prevent memory leaks that require generational GC sweeps.
Mock Test · 1 Questions · Optional
Ready for Type Hints?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions