Recursion & the call stack
Write correct recursive functions with clear base cases and trace them on the call stack.
By Invicly Tech, , in Data Structures & Algorithms. About 11 minutes to read.
In short
A recursive function solves a problem by calling itself on a smaller version until it reaches a base case it can answer directly. Each call gets its own frame on the call stack, which unwinds as calls return. Drawing the recursion tree shows both the result and the cost.
Think of it like this: Russian nesting dolls: open each doll until you reach the solid one, then close them back up.
Explained simply
Recursion means a function calls itself. That sounds like a loop that never ends, but there is a rule: every call works on a smaller piece of the problem, and there is a smallest piece that the function answers directly. That smallest piece is the base case.
Think of counting people in a long queue without leaving your spot. You ask the person behind you, "How many people are behind you?" They ask the person behind them, and so on. The last person says "zero" (the base case). Each person adds one and passes the answer forward.
While all this asking happens, each person has to wait and remember their place. A computer does the same with the call stack. Every call gets a frame, a small block of memory holding its local variables and where to return. When a call finishes, its frame is removed.
The stack has a limit. Python stops at about 1000 nested calls and raises RecursionError. So recursion is great for trees and divide-and-conquer, where depth stays small, but risky for walking a list of a million items one at a time.
Any recursive function can be rewritten with a loop and your own stack. Learning to switch between the two styles is one of the most useful skills in algorithms.
Press Play on a diagram to walk through it one step at a time.
- fib(3)
- fib(2)
- fib(1)
- fib(2)
- fib(1)
- fib(0)
- Mirrors the definition
- Stack managed by Python
- Limited to about 1000 deep
- Short code for trees and backtracking
- You manage the stack list
- Depth limited only by memory
- Faster in Python
- More code, easier to get order wrong
In depth
Writing a correct recursive function
Use a three-question checklist. First, what is the smallest input I can answer without recursing? That is the base case, for example an empty list or n == 0. Second, how do I make the input smaller? Slice off one item, halve the range, or move to a child node. Third, if I trust that the recursive call returns the right answer for the smaller input, how do I build my answer from it?
The third step is the leap of faith. Do not trace every level in your head. Prove the base case is right, prove each step combines correctly, and induction does the rest.
Watch for progress. sum_list(a) = a[0] + sum_list(a[1:]) shrinks by one each call, so it ends. A call like f(n) = f(n) + 1 never shrinks and only stops when the stack overflows.
- Base case first, at the top of the function
- Every call must move towards the base case
- Trust the recursive call; check only the combine step
What happens on the call stack
Each call pushes a frame holding its arguments, local variables and the point to resume. The caller pauses until the callee returns. So the stack grows on the way down and shrinks on the way back up, and the deepest point decides the memory used: O(depth).
Take factorial(3). The stack grows to factorial(3), factorial(2), factorial(1). factorial(1) returns 1, its frame is popped, factorial(2) resumes and returns 2, and finally factorial(3) returns 6.
The work done after the recursive call returns is the unwinding phase. In n * factorial(n - 1), the multiplication happens on the way up. A call that is the very last action, like return helper(n - 1, acc * n), is a tail call. Some languages reuse the frame for tail calls, but Python never does, so a tail-recursive Python function still uses O(n) stack.
- factorial(3) to factorial(2): call with n = 21call with n = 2
- factorial(2) to factorial(1): call with n = 12call with n = 1
- factorial(1) to factorial(2): base case: return 13base case: return 1
- factorial(2) to factorial(3): return 2 * 1 = 24return 2 * 1 = 2
Recursion trees and their cost
Draw each call as a node and its recursive calls as children. Total time is the sum of the work at every node. Maximum stack space is the height of the tree.
For a single recursive call per level, like factorial, the tree is a path: n nodes, O(n) time, O(n) space. For two calls on n - 1, like naive Fibonacci or Tower of Hanoi, the tree roughly doubles each level. Hanoi with n disks makes exactly 2^n - 1 moves. Naive fib(n) makes 2 * fib(n + 1) - 1 calls, which grows like 1.618^n, yet uses only O(n) stack because only one path is active at a time.
For two calls on n / 2 with O(n) extra work, like merge sort, the tree has log2 n levels, each doing O(n) total work: O(n log n).
- Time = sum of work at all nodes
- Space = depth of the tree (plus any copies made)
- Repeated identical subtrees mean memoisation will help
Python's recursion limit and hidden costs
sys.getrecursionlimit() returns 1000 by default. You can raise it with sys.setrecursionlimit(10_000), but that only moves the guard rail. Very deep recursion can still crash the interpreter if the underlying C stack runs out, so for depths in the hundreds of thousands, switch to iteration.
Two hidden costs often surprise people. Slicing, as in f(a[1:]), copies the list every call, turning an O(n) algorithm into O(n^2) time and memory. Pass indexes instead: f(a, i + 1). And building strings by concatenation in each call has the same problem.
Function calls in Python are also relatively slow, roughly tens of nanoseconds each in recent versions. For hot inner loops, an iterative version is often several times faster. Memoising with @functools.cache (Python 3.9 and later) removes repeated calls entirely when subproblems repeat.
- Default limit: 1000 frames
- Pass indexes, not slices
- @functools.cache turns repeated subcalls into dict lookups
Turning recursion into iteration
There are two common conversions. If the function does its work on the way down and has only one recursive call, a simple loop works: keep the changing values in variables and update them each pass. Tail-recursive functions always convert this way.
If there are several recursive calls, or work after the call, use an explicit stack. Push the starting input. Loop: pop an item, process it, and push its sub-items. This is exactly what the call stack was doing, but now the stack is a Python list on the heap, which can hold millions of items.
When the result needs work after children finish (post-order), push a marker. A common trick is pushing (node, True) to mean "children are done, now combine". The iterative version is longer but cannot hit RecursionError.
- 1Push start
stack = [root input]
- 2Pop
Take the most recent item.
- 3Process
Do the work for this item.
- 4Push children
Smaller sub-inputs go on the stack.
- 5Repeat
Until the stack is empty.
- Back to step 1
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Identify base case and recursive case~35m
- 2Trace calls on the call stack~35m
- 3Draw recursion trees~35m
- 4Know Python's recursion limit~35m
- 5Convert simple recursion to iteration~35m
Key points
- Every recursion needs a base case and progress towards it.
- Naive fib is O(2^n) because subproblems repeat; memoisation makes it O(n).
- Stack space is O(maximum depth).
- Python's default recursion limit is about 1000 frames.
Key terms
Tap a card to flip it. 0/4 known
Examples
def factorial(n): # O(n) time, O(n) stack
if n <= 1: # base case
return 1
return n * factorial(n - 1) # smaller subproblem
def sum_digits(n):
return n if n < 10 else n % 10 + sum_digits(n // 10)
print(factorial(5), sum_digits(1234)) # 120 10Tower of Hanoi: 2^n - 1 moves
To move n disks from peg A to peg C, move the top n - 1 disks to B, move the biggest disk to C, then move the n - 1 disks from B to C. The base case is zero disks, which needs no moves. The number of moves obeys M(n) = 2M(n - 1) + 1 with M(0) = 0, so M(n) = 2^n - 1. For 3 disks that is 7 moves; for 64 disks it is more than 18 quintillion.
def hanoi(n, src, dst, via, moves):
if n == 0:
return
hanoi(n - 1, src, via, dst, moves)
moves.append((src, dst))
hanoi(n - 1, via, dst, src, moves)
moves = []
hanoi(3, 'A', 'C', 'B', moves)
print(len(moves), moves[:3]) # 7 [('A', 'C'), ('A', 'B'), ('C', 'B')]Flattening nested lists, recursive and iterative
A nested list like [1, [2, [3, 4]], 5] is itself recursive: each item is a number or another list. The recursive version reads naturally. The iterative version uses a stack of iterators so it handles nesting thousands of levels deep without RecursionError. Both return [1, 2, 3, 4, 5].
def flatten(x):
if not isinstance(x, list):
return [x]
return [y for item in x for y in flatten(item)]
def flatten_iter(x):
out, stack = [], [iter(x)]
while stack:
item = next(stack[-1], StopIteration)
if item is StopIteration: stack.pop()
elif isinstance(item, list): stack.append(iter(item))
else: out.append(item)
return out
print(flatten([1, [2, [3, 4]], 5]), flatten_iter([1, [2, [3, 4]], 5]))Quick reference
- Every recursive function needs a base case and a step that shrinks the input
- Stack space = maximum recursion depth, not total number of calls
- sys.getrecursionlimit() is 1000 by default; sys.setrecursionlimit() raises it
- Python never optimises tail calls
- Pass index ranges instead of slices to avoid O(n) copies per call
- Naive fib(n) makes 2 * fib(n + 1) - 1 calls; @functools.cache makes it O(n)
- Iterative rewrite: a list as the stack, pop, process, push sub-problems
Common mistakes
- Missing or unreachable base cases, causing RecursionError.
- Recursing on inputs that do not get smaller.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write is_palindrome(s, i, j) recursively, checking s[i..j] without slicing. Example: is_palindrome('racecar', 0, 6) is True, is_palindrome('abca', 0, 3) is False.
- Exercise 2medium
Write power(x, n) for integer n >= 0 using recursion in O(log n) multiplications. Example: power(2, 10) is 1024.
- Exercise 3hard
Write subsets(a) that returns all subsets of a list, first recursively, then convince yourself of the count: a list of n items has 2^n subsets. Example: subsets([1, 2, 3]) has 8 entries.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is recursion slower than a loop?
- In Python, usually yes, because each call creates a frame and calls cost tens of nanoseconds. The difference only matters in hot code; choose the clearer version first.
- How do I fix RecursionError: maximum recursion depth exceeded?
- First check the base case is reachable. If the depth is genuinely large, rewrite with an explicit stack; raising sys.setrecursionlimit is a short-term patch.
- What is the difference between recursion and dynamic programming?
- Recursion is a way to write a function. Dynamic programming is recursion (or iteration) where overlapping subproblems are stored and reused, so each is solved once.