Python: Memory Management & Garbage Collection
If you want to write better code in Python, it's important to understand this topic well.
This post might have some inaccuracies. Please feel free to research and explore on your own!
Garbage Collection
In English, "Garbage Collection" is the process of collecting unreferenced objects that are no longer in use. But when can something be considered garbage? It's simple—when you can no longer use an object or value, you consider it garbage.
But why do we need a Garbage Collector? Without it, memory would fill up quickly. If you don't want your computer's memory to explode, then the Garbage Collector is essential 🙃.
Reference Count
As humans, it's easy to understand garbage. You buy a bottle of water, drink it, and know that the bottle is no longer useful to you—it's now garbage. In programming, after a value or object is created, its reference count is calculated, which means how many variables are pointing to it.
# An object 1 is created in memory
x = 1
print(x)
# When you delete the variable, the reference to 1 is gone
del x
You might think variables store values, but they actually just provide references to those values.
The sys library function sys.getrefcount() can show how many references an object has.
import sys
x = [4, 3, 2, 1]
print(sys.getrefcount(x)) # Returns 2 (one for x, one for the function argument)
y = x
print(sys.getrefcount(x)) # Returns 3
Determining Identity
Did you know that Python compares two objects in constant time, O(1)? Python doesn't compare the values of objects; it compares their memory addresses.
a = 257
b = 257
print(a is b) # False (Wait, what? Because small integers are cached, but 257 is not always!)
Conclusion
Memory management in Python involves a private heap containing all Python objects and data structures. The management of this private heap is ensured internally by the Python memory manager.
Similar Posts
Django: Signals vs Overriding Save
Sep 14, 2025
Python: The 'with' Statement
Aug 21, 2025
Docker: Init Systems (PID 1)
Jul 11, 2025