Sub topic 9
The call stack and recursion
This chapter assumes you can write recursive functions in Python, know what a stack's push and pop do, and understand Big-O notation. It explains how a running program uses a stack to track function calls, and why deep recursion can fail.
What the call stack stores
When a function is called, the runtime creates a stack frame. The frame holds the function's arguments, its local variables, and the place to resume in the caller. The runtime pushes the frame onto the call stack. When the function returns, the runtime pops its frame and continues in the caller.
Calls and returns nest, so the most recent call always finishes first. That is last in, first out, so a stack fits.
Tracing a recursive call
Consider a factorial function.
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(3)) # 6The call factorial(3) pushes a frame, and that frame calls factorial(2), which calls factorial(1). The base case returns first, and each frame is popped as its result is used.
At the deepest point, three factorial frames sit above main. Each frame holds its own n, so the calls do not interfere with each other. The multiplication n * ... waits in each frame until the call below it returns.
Stack overflow
The call stack has a fixed size limit. If recursion goes too deep, or never reaches a base case, the stack runs out of room. This is a stack overflow. It is a different error from the overflow of a data structure you wrote yourself, which the earlier chapter on errors covered.
Python guards against this with a recursion limit, 1000 by default. Exceeding it raises RecursionError.
import sys
def count_down(n):
return count_down(n - 1) # no base case
try:
count_down(5)
except RecursionError:
print("limit:", sys.getrecursionlimit())Other languages differ. In C or Java, the program may crash or throw StackOverflowError once the stack memory is used up.
Cost of recursion
Each active call uses memory. A recursion of depth n uses O(n) stack space, even if the function allocates nothing else. Recursion also adds the overhead of creating and removing frames.
| Version | Time | Extra space |
|---|---|---|
| Recursive factorial | O(n) | O(n) frames |
| Loop-based factorial | O(n) | O(1) |
Replacing recursion with a stack
Any recursion can be rewritten with an explicit stack that you control. The stack lives on the heap, so its size is limited by available memory, not by the recursion limit. This sketch shows the idea for factorial.
def factorial_iter(n):
stack = []
while n > 1:
stack.append(n)
n -= 1
result = 1
while stack:
result *= stack.pop()
return result
print(factorial_iter(5)) # 120The first loop plays the role of the calls going down. The second loop plays the role of the returns coming back up. A later chapter uses this same technique for depth-first search.
Common mistakes
- Forgetting the base case, or writing one the input can never reach.
- Recursing on a problem that does not get smaller, such as calling
f(n)instead off(n - 1). - Assuming recursion is free. Depth costs memory.
Exercise
A function sums a list recursively by adding the first element to the sum of the rest. How much call stack space does it use for a list of length n, and what happens for a list of 5,000 elements in default Python?
Show answer
It uses O(n) stack space, one frame per element. With 5,000 elements the depth exceeds the default limit of 1000, so Python raises RecursionError. An iterative loop or an explicit stack avoids this.