Skip to content

What the call stack does during recursion

BasicsUnder the hood

A recursive function calls itself, yet each call keeps its own n and picks up exactly where it left off. Here is the stack of frames that makes that work, drawn one push and one pop at a time.

01 A function that calls itself

Here is factorial written the recursive way. fact(3) works out 3 * fact(2), which works out 2 * fact(1), which is just 1.

fact.py
def fact(n):
if n == 1:
return 1
return n * fact(n - 1)
print(fact(3)) # 6

The puzzle: when fact(1) returns, how does the program know it was in the middle of 2 * …, and that n was 2 there? The inner calls used n too.

02 The wrong picture: one shared n

If there were only one n for the function, each call would overwrite it. By the time fact(1) set n = 1, the 3 and the 2 would be lost, and every multiplication on the way back would use 1.

One shared n
fact(3): n = 3
fact(2): n = 2 (3 is overwritten)
fact(1): n = 1 (2 is overwritten)
back in fact(2): 1 * 1 = 1
back in fact(3): 1 * 1 = 1
A frame per call
fact(3): its own n = 3
fact(2): its own n = 2
fact(1): its own n = 1
back in fact(2): 2 * 1 = 2
back in fact(3): 3 * 2 = 6

What really happens is the right-hand side. Every call gets a fresh, private set of variables, kept in a frame.

03 Each call gets its own frame

The frames are kept on the call stack. A call pushes a new frame on top. Only the top frame runs; the ones below are paused mid-line. A return pops the top frame and hands its value to the one below, which carries on.

fact(3), one push or pop per step
Step 1 of 7
Call stack · top is running
Empty
Values returned so far
Empty
  • frame just pushed
  • running again
  • paused, waiting
  • final answer

Nothing has run yet. The stack is empty, and nothing has been returned.

0 depth

Last in, first out: fact(1) was pushed last and returned first. That is the whole reason it is a stack.

04 What a frame holds

The parts of one frame, for fact(2)
PartIn fact(2)Why it is needed
Argumentsn = 2Each call was passed its own value.
Local variables(none here)Anything assigned inside the call lives here too.
Where to resumeline 4, in the middle of n * …So the call can carry on after the inner call returns.
Who called itfact(3)'s frameSo the return value goes to the right place.

In C, Java or Go, frames typically sit in a block of memory each thread reserves for this, also called the stack. CPython keeps its own frame records rather than using the machine stack directly, but they are pushed and popped in exactly the same order.

05 Two calls per frame, one path at a time

fib(n) calls itself twice: fib(n - 1) + fib(n - 2). That looks as if the stack should hold both branches at once. It does not. The left call runs to the end and is popped before the right one starts.

fib.py
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
fib(3): the stack holds one root-to-node path
Step 1 of 11
Stack depth 0
Call stack · top is running
Empty
Call tree · every call made
fib(3)
fib(2)
fib(1)
fib(0)
fib(1)
  • just called
  • running
  • on the stack, waiting
  • returned
  • not called yet
  • paused frame

Before the call. The tree shows every call fib(3) will make; none has happened yet.

0 calls made
Stack depthAbout nThe longest path in the call tree. Memory used by frames grows with this.
Calls madeGrows exponentiallyEvery node in the tree. Plain fib repeats the same calls many times, which is why it is slow, not why it crashes.

06 Watch the stack in Python

Pass the depth down and indent by it. Each call line is a push; each returns line is a pop. The returns come out in the reverse order of the calls.

trace_fact.py
def fact(n, depth=0):
pad = " " * depth
print(f"{pad}call fact({n})")
if n == 1:
result = 1
else:
result = n * fact(n - 1, depth + 1)
print(f"{pad}fact({n}) returns {result}")
return result
fact(3)
Text
call fact(3)
call fact(2)
call fact(1)
fact(1) returns 1
fact(2) returns 2
fact(3) returns 6

A crash traceback is the same picture, printed for you: one line pair per frame that was on the stack when the error happened, oldest first.

07 When the stack runs out

def fact(n): return n * fact(n - 1)No base caseNothing ever returns, so frames pile up until the limit. CPython stops at a recursion limit (sys.getrecursionlimit() is 1000 by default) with RecursionError; Java throws StackOverflowError.
fact(0)A base case the input never reachesfact(0) goes to -1, -2, … and never hits n == 1. Guard with n <= 1.
walk(node.next) # 100,000 nodesCorrect, but too deepRecursing once per item of a long list needs one frame per item. Past a few thousand, use a loop or an explicit stack you manage yourself.
def add(x, seen=[]): seen.append(x)Frames hold names, not copiesEach frame has its own variable names, but they can point at the same list. A change made deep down is visible to every frame that shares it.

A deep stack is about depth, not about the number of calls. fib(30) makes over a million calls but is never more than 30 frames deep, so it is slow but does not overflow.

08 Check yourself

Question

While fact(1) is running inside fact(3), how many frames for fact are on the stack?

Question

fib(5) makes 15 calls. What is the most frames it has on the stack at once?

Question

Calls are made in the order A, B, C, each from the one before. In what order do they return?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?