3. Reference Counting
Python primarily uses reference counting to manage memory.
Example
import sys
x = []
print(sys.getrefcount(x)) # includes temporary reference in getrefcount
y = x
print(sys.getrefcount(x))
Issues
- Cyclic references cannot be collected by reference counting alone.
- Garbage collector is needed to handle cycles.
Wrap-Up
Reference counting is simple but insufficient for cycles, which is why Python also uses garbage collection.