6.3 Memory Management: Stack vs Heap
How CPython splits memory between the call stack (frame references) and the heap (actual object data), and why that split explains reference semantics when passing variables into functions.
Stack vs Heap
What Is It?
The stack holds function call frames — each frame stores its local variable names and the references they point to. The heap is where the actual objects (their real data) live.
Why Does It Matter?
Understanding this split explains why passing a variable into a function passes a reference, not a full copy of the data — the deep dive on that is 6.10 Variables in Functions.
The stack holds references (pointers); all actual objects, mutable or immutable, live on the heap.
Memory Allocation
How Is It Used?
When you create an object — a literal, a constructor call, and so on — CPython allocates space for it on the heap and returns a reference to that location, which gets stored in whatever variable or frame is holding it.
>>> x = 42 # 42 is allocated on the heap; x (in the current frame) references it
Memory Deallocation
Once an object’s reference count drops to zero — no variable, container, or frame references it anymore — CPython frees its heap memory automatically. This is why Python has no manual free() call like C; the mechanics are covered fully in 6.6 Garbage Collection.
Object Lifetime
An object exists from creation until its last reference disappears — via reassignment, del, or the referencing scope ending (see 6.9 Lifetime of Variables) — at which point it becomes eligible for garbage collection.
Quick Interview Answer
“CPython splits memory into the stack, which holds function call frames and the references their local variables point to, and the heap, where the actual object data lives. Every object — whether an
int, alist, or a custom class instance — is allocated on the heap; only the reference to it sits on the stack frame. This is why passing a variable into a function passes a reference to the same heap object, not a copy of it.”
Common Mistakes
- Assuming Python has stack-allocated value types the way C or Go do — in CPython, every object lives on the heap; the stack only ever holds references.
- Confusing “the stack” (call frames) with “the call stack” shown in a traceback — related, but a traceback shows the sequence of frames, not memory layout details.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form