Python Basics

Python Memory Management

How Python manages memory under the hood

Python Memory Management

Understanding how Python manages memory helps you write efficient, bug-free programs. Python uses a combination of reference counting and a garbage collector to automatically free memory you no longer use.

Objects and References

In Python, everything is an object. Variables are references (labels) that point to objects stored in memory:

a = [1, 2, 3]
b = a      # b references the same list object as a

print(id(a), id(b))  # same memory address

Multiple variables can point to the same object. Changing the object through one reference is visible through all references.

Reference Counting

Python keeps a reference count for each object. When the count goes to zero (no references), the object becomes eligible for deletion.

import sys

x = [1, 2, 3]
print(sys.getrefcount(x))  # number of references to x

Tip: You almost never need to manage reference counts manually in normal Python code.

Garbage Collector

Reference counting has problems with reference cycles (two objects referring to each other). Python has a gc (garbage collector) module to handle these cases:

import gc

# Force a garbage collection run
gc.collect()

Mutable vs Immutable

Some objects are immutable (cannot be changed in-place), like int, str, and tuple. Others are mutable like list, dict, and set. This affects how memory is used:

# Immutable
x = 10
y = x
x = x + 1   # creates a new int object

# Mutable
nums = [1, 2, 3]
alias = nums
alias.append(4)  # modifies the same list object

Memory Leaks in Python

Pure Python code rarely has classic memory leaks, but you can still see memory growth if you:

  • Keep unnecessary references alive (e.g., large lists stored globally)
  • Accidentally create reference cycles involving objects with __del__ methods
  • Use C-extensions that allocate memory outside Python's control

Best Practices

  • Limit long-lived global variables
  • Use local variables inside functions where possible
  • Close files, network connections, and database cursors
  • Use context managers (with statements) to release resources deterministically