Quiz
Warm-up from lesson 3-1: two processes run the same program. Process A changes a variable. Why does process B not see the change?
Inside one process's memory
This layout is worth learning because it explains, precisely, the most common beginner bug in Python ("why did my list change when I modified a different variable?"), what a stack trace is actually showing you, and why the crashes in the next lesson happen. It is also a perennial interview topic.
The RAM a process owns is organized into regions. The two you must know:
- The stack holds function calls. Every time a function is called, a frame is pushed on top: its parameters, its local variables, and where to return to. When the function returns, its frame is popped off. Last in, first out, like a stack of plates.
- The heap holds data whose lifetime is not tied to one function call: your lists, dictionaries, and objects. Things on the heap live until nothing points at them anymore.
In Python, local names live in stack frames, but the objects they point to (lists, dicts, strings, numbers) live on the heap. A variable is an arrow from a frame to a heap object.
Two arrows, one object
The figure shows the trap this model predicts: b = a does not copy the list. It copies the arrow. Both names now point at the same heap object, so a change made through either name is visible through both.
This is the number one "why did my data change?!" bug for Python beginners, and now you can see exactly why it happens. Python checks identity with the is operator: a is b asks "are these two arrows pointing at the same heap object?"
Code exercise · python
Run this. b = a copies the arrow, not the list, so appending through b changes what a sees too.
Code exercise · python
Your turn. Make d a real COPY of c (a new heap object), append 4 to d, then print c, d, and whether c is d. c must stay [1, 2, 3].
Quiz
Where does the list object created by nums = [1, 2, 3] inside a function live, and where does the name nums live?