01 / 21

Recursion
Depth Limits

Understand why Python caps recursive calls, what happens when you exceed the limit, and how to write safe recursive code that avoids stack overflow.

Python

What is Recursion?

A function is recursive when it calls itself to solve a smaller instance of the same problem. Each call creates a new stack frame: a block of memory that stores the function's local variables, parameters, and return address.

def factorial(n): if n <= 1: return 1 return n * factorial(n - 1)

The Call Stack Visualized

factorial(5) factorial(4) factorial(3) factorial(2) factorial(1) → returns 1 STACK GROWS Depth 1 Depth 2 Depth 3 Depth 4 Depth 5 Each frame consumes memory until it returns

The stack grows downward with each recursive call. Frames are removed (popped) only when the base case returns and results propagate back up.

Why Does Python Set a Limit?

Your operating system allocates a fixed amount of stack memory for each program (typically 1-8 MB). If recursion goes too deep, the stack overflows and your program crashes. Python prevents this by enforcing a maximum recursion depth.

Protection
Stops infinite recursion from crashing the OS or consuming all memory.
Default Limit
Python's default is 1,000 recursive calls deep (CPython).
Consequence
Exceeding it raises a RecursionError and halts execution.

The RecursionError

def countdown(n): print(n) countdown(n - 1) # No base case! countdown(5)
RecursionError: maximum recursion depth exceeded while calling a Python object

The Recursion Limit Rule

import sys print(sys.getrecursionlimit()) # → 1000 # You CAN change it (but usually shouldn't): sys.setrecursionlimit(2000)

How Depth Grows with Input

0 250 500 750 1000 LIMIT 0 200 400 600 800 1000
factorial(\( n \)): depth = \( n \)
Input value (n) Recursion depth

For factorial(\( n \)), depth grows linearly: \( \text{depth} = n \). So factorial(1000) hits the limit exactly. Algorithms like naive Fibonacci have the same depth issue.

Recursion vs. Iteration

Recursion Iteration
Memory New frame per call Constant stack
Depth limit ~1,000 calls No limit
Readability Often cleaner for trees, graphs Clearer for linear tasks
Risk RecursionError Infinite loop (if no exit)
Speed Function call overhead Faster for simple cases

How to Stay Safe

1
Always include a base case. Every recursive function must have a condition that stops recursion without making another call.
2
Ensure progress toward the base case. Each recursive call must bring the argument closer to the terminating condition.
3
Estimate your maximum depth. If \( n \) can be large (e.g., \( n > 900 \)), prefer an iterative approach.
4
Use memoization wisely. Caching results reduces repeated calls but does not reduce maximum depth.
5
Convert deep recursion to iteration. Use an explicit stack (a Python list) to simulate the call stack yourself.

Example 1: Safe Factorial

def factorial(n): if n <= 1: # Base case ✓ return 1 return n * factorial(n - 1) # Progress ✓ print(factorial(5)) # → 120 (depth = 5, well under 1000)

Example 2: Dangerous Recursion

def sum_to(n): if n == 0: return 0 return n + sum_to(n - 1) print(sum_to(500)) # → 125250 ✓ OK print(sum_to(1500)) # → RecursionError ✕

Example 3: Converting to Iteration

# Recursive (limited to ~1000) def factorial_rec(n): if n <= 1: return 1 return n * factorial_rec(n - 1) # Iterative (no depth limit) def factorial_iter(n): result = 1 for i in range(2, n + 1): result *= i return result print(factorial_iter(5000)) # ✓ Works fine!

The Explicit Stack Pattern

When the recursive structure is complex (e.g., tree traversal), you can simulate recursion using a Python list as a stack:

# Recursive DFS def dfs_rec(node): if node is None: return process(node) dfs_rec(node.left) dfs_rec(node.right) # Iterative DFS (no depth limit) def dfs_iter(root): stack = [root] while stack: node = stack.pop() if node is None: continue process(node) stack.append(node.right) stack.append(node.left)

Memoization ≠ Depth Fix

Without Memoization fib(5) fib(4) fib(3) fib(3) fib(2) fib(2) Redundant calls, same depth With Memoization fib(5) fib(4) fib(3) fib(2) fib(1) → 1
Fewer calls, but depth = \( n \)
Memoization reduces time complexity, NOT stack depth

Memoization (e.g., @functools.lru_cache) avoids redundant computations, but the longest chain of nested calls remains the same: \( n \) levels deep.

Common Mistakes

✕ Missing Base Case
Forgetting to include a terminating condition, causing infinite recursion until Python stops it.
✕ No Progress
The recursive call passes the same or larger argument, never approaching the base case.
✕ Blindly Raising Limit
Using sys.setrecursionlimit(10**6) without understanding it may cause a real stack overflow crash.

Quick Reference Summary

Concept Key Detail
Default limit 1,000 frames
Check limit sys.getrecursionlimit()
Change limit sys.setrecursionlimit(n) (use cautiously)
Error raised RecursionError
Best fix Convert to iteration or use explicit stack
Memoization Reduces time, not depth
Safe practice Base case + progress + depth estimate

Question 1 of 5

What is the default maximum recursion depth in CPython?

Question 2 of 5

Which error does Python raise when the recursion depth limit is exceeded?

Question 3 of 5

A recursive function has a correct base case but the recursive call passes \( n + 1 \) instead of \( n - 1 \). What will happen?

Question 4 of 5

Which strategy eliminates the risk of hitting the recursion depth limit?

Question 5 of 5

What is the maximum recursion depth when calling factorial(750) with a standard recursive implementation?