Memory Management
Overview
Unlike C++, where you must manually allocate and free() memory, Python handles memory autonomously. It uses a dual system: Reference Counting and a Garbage Collector. Every object keeps a 'reference count' of how many variables are pointing to it. When that count drops to zero, Python instantly destroys the object and reclaims the RAM. The secondary Garbage Collector runs periodically specifically to hunt down 'cyclic references' (where Object A points to Object B, and Object B points back to Object A) that the reference counter cannot resolve.
Syntax
import sys
my_list = [1, 2, 3]
# The list currently has 1 reference (my_list).
# Note: getrefcount temporarily adds 1 reference while executing.
print(sys.getrefcount(my_list)) # 2
# Create a second reference
alias_list = my_list
# Drop references
del my_list
# The list is NOT destroyed yet because alias_list still points to it.
del alias_list
# Reference count hits 0. Memory is instantly freed!Common Pitfalls
- Memory Leaks via Global Scope: If you append massive datasets to a global list (like a cache) and never clear it, the reference count never drops to zero, permanently consuming RAM.
- Assuming
delerases objects.del var_namesimply deletes the variable name from the namespace, which drops the reference count by 1. The object is only erased if the count hits zero.
Interview Questions
A reference cycle occurs when objects reference each other (e.g., doubly linked lists), preventing their reference counts from ever reaching zero. Python's cyclic Garbage Collector runs periodically to detect and destroy these isolated islands of memory.
Real-World Example
Using the weakref module to build caches that don't artificially keep objects alive.
import weakref
class HeavyData:
pass
data = HeavyData()
# Creating a weak reference does NOT increase the reference count.
# If 'data' is deleted elsewhere, this cache will automatically empty itself.
cache = weakref.ref(data)Check Your Knowledge
Test your understanding of Memory Management with these quick questions.