Heaps and stacks in Python

TL;DR: Heaps are where a Python program stores its data. Stacks are where the computations happen. This post breaks down what happens in RAM when Python runs a simple script.
The Script:
name = "Eli" x = 2 + 3 y = sorted([name, x])
Step 1: python script.py
When I first run the script via PowerShell:
- The Windows kernel creates a Python process, allocates a memory block on RAM and provides the process with acces to that block via virtual memory.
- Python:
- creates heap memory in RAM that includes built-in functions, core class objects (e.g. list, dict), small integers, and other essential objects like True, False, and None.
- creates the __main__ stack frame in memory.
Step 2: name = "Eli"
- In heap memory, python creates a string object
"Eli"
. - In stack, python creates and stores a reference to that object under the name
name
in the__main__
stack frame.
Step 3: x = 2 + 3
- Python accesses the pre-stored interger objects
2
and3
from heap, and adds them using a bytecode operation, and stores the result in the heap, if not already cached. - In the current stack frame,
x
is bound to the integer object5
.
Step 4: y = sorted([name, x])
- In heap, a new
list
object is created in heap memory for[name, x]
, referencing the existant values ofname
andx
. - In the current stack frame, the identifier
y
is created. - Python creates a new temporary stack frame for the
sorted()
function, with a reference to thesorted
function and a reference to the[name, x]
list in heap memory. - The
sorted()
frame is executed, and the result is popped out and stored in heap memory. - The identifier
y
in the main stack frame is bound to the new sortedlist
object in heap.
By the end of this script, my __main__
stack frame contains three variables: name
, x
, and y
, each pointing to heap-allocated objects: "Eli"
, 5
, and [x, name]
.
Sources & Links
- Python: Stack and Heap Memory
- Exploring Python’s Memory Management: Behind the Scenes
- Python Memory Management: The Essential Guide