Recursion · 4 / 18 Theory

The call stack and the recursion limit

To write recursive functions without surprises you need to know what happens inside Python each time a function calls itself.

The call stack

Each function call creates a frame with its local variables and stacks it on top of the previous ones. When the function ends, its frame is removed and the previous one resumes. With recursion, calls pile up until the base case and then are resolved in reverse order.

def countdown(n):
    print("enter", n)
    if n > 0:
        countdown(n - 1)
    print("leave", n)

countdown(2)
# enter 2
# enter 1
# enter 0
# leave 0
# leave 1
# leave 2

That “enter… leave” in reverse order is the key to problems such as Towers of Hanoi: the work left pending when returning from each call also counts.

The base case is mandatory

Every recursion needs at least one base case that does not call itself and a recursive step that moves toward it. If the base case is missing, or the data do not get closer to it, the stack grows endlessly.

The recursion limit

Python limits the depth of the stack (1000 calls by default, sys.getrecursionlimit()). When exceeded it raises RecursionError. It is a protection: each frame uses memory.

# Not run in the corrector: it deliberately reaches the recursion limit.
import sys

def endless(n):
    return endless(n + 1)      # it has no base case

print(sys.getrecursionlimit())  # 1000 (by default)
try:
    endless(0)
except RecursionError:
    print("Too many nested calls")

The limit can be raised with sys.setrecursionlimit(), but it is almost always better to change the algorithm.

Recursion versus loops

If the problem is linear and the depth can be large, a loop is more efficient and has no limit. Recursion shines when the data has a tree shape (nested lists, folders, expressions) or the problem splits into subproblems.

def recursive_sum(n):
    return 0 if n == 0 else n + recursive_sum(n - 1)

def loop_sum(n):
    total = 0
    for i in range(1, n + 1):
        total += i
    return total

print(recursive_sum(100), loop_sum(100))   # 5050 5050
print(loop_sum(1_000_000))                  # 500000500000 (recursion would give RecursionError)

A clear example of tree-shaped data is Flattening nested lists.

When subproblems repeat

Naive recursion can solve the same subproblem many times (like fib(n-1) and fib(n-2)). The solution is to store the results: memoization. In Ways to climb stairs, without memory the time explodes; with it, it is instant.