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.
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.
The Call Stack Visualized
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.
The RecursionError
The Recursion Limit Rule
How Depth Grows with Input
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
Example 1: Safe Factorial
Example 2: Dangerous Recursion
Example 3: Converting to Iteration
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:
Memoization ≠ Depth Fix
Memoization (e.g., @functools.lru_cache) avoids redundant computations, but the longest chain of nested calls remains the same: \( n \) levels deep.
Common Mistakes
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?