Recursion is when a function solves a problem by calling itself on a smaller piece of it, until it reaches a base case it can answer directly. Every recursive function needs two parts: a base case that stops, and a recursive step that moves closer to it.
def factorial(n):
if n <= 1: # base case: answer directly
return 1
return n * factorial(n - 1) # recursive step: smaller input
print(factorial(5)) # 120
How a recursive call actually runs
factorial(5) can't finish until it knows factorial(4), which needs factorial(3), and so on. Each waiting call sits on the call stack with its own copy of n:
factorial(5) = 5 * factorial(4)
factorial(4) = 4 * factorial(3)
factorial(3) = 3 * factorial(2)
factorial(2) = 2 * factorial(1)
factorial(1) = 1 (base case)
factorial(2) = 2 * 1 = 2
factorial(3) = 3 * 2 = 6
factorial(4) = 4 * 6 = 24
factorial(5) = 5 * 24 = 120
The calls go down until the base case returns, then the results come back up, each waiting call finishing its multiplication. Five calls are on the stack at the deepest point. That stack depth is the cost of recursion, and it is what eventually breaks.
The error you get when recursion goes wrong
Here is a function with no base case:
def broken(n):
return broken(n - 1)
broken(10)
Real output from Python 3.12.2 (path shortened):
Traceback (most recent call last):
File "C:\work\rec.py", line 33, in <module>
broken(10)
File "C:\work\rec.py", line 32, in broken
return broken(n - 1)
^^^^^^^^^^^^^
File "C:\work\rec.py", line 32, in broken
return broken(n - 1)
^^^^^^^^^^^^^
File "C:\work\rec.py", line 32, in broken
return broken(n - 1)
^^^^^^^^^^^^^
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
Python collapsed the repeated frames into [Previous line repeated 996 more times]. The Python documentation describes RecursionError as a subclass of RuntimeError, raised when the interpreter detects that the maximum recursion depth is exceeded. Before Python 3.5, the same situation raised a plain RuntimeError.
When you see it, the cause is almost always one of these:
- No base case, as above.
- A base case that is never reached.
factorial(-1)with a base case ofn == 0counts down forever: -2, -3, -4. Usen <= 0or validate the input. - A step that doesn't shrink the input, for example calling
f(n)instead off(n - 1), or passing the same list back unchanged. - Accidental recursion, such as a property or
__getattr__that reads itself, or two functions that call each other with no exit. - Correct recursion on deep input: walking a linked list of 5,000 nodes, or a deeply nested JSON structure. The code is fine; the depth isn't.
The traceback shows which line keeps repeating. Reading it from the bottom up is the same skill as in how to read a stack trace.
Python's recursion limit
import sys
print(sys.getrecursionlimit()) # 1000 on our Python 3.12.2 install
The Python documentation describes the limit as the maximum depth of the interpreter stack, there to stop infinite recursion from overflowing the C stack and crashing Python. You can change it with sys.setrecursionlimit(), but the same page warns that the highest safe value is platform-dependent and that a limit set too high can crash the interpreter. Raising it is a reasonable fix for a correct algorithm that needs a few thousand levels; it is not a fix for a missing base case.
Python also doesn't remove the stack frame for a tail call (a recursive call that is the very last thing a function does). This function is tail-recursive, works for 500, and still fails past the limit:
def countdown(n):
if n == 0:
return "done"
return countdown(n - 1)
countdown(500) # 'done'
countdown(5000) # RecursionError: maximum recursion depth exceeded
Measured: when recursion repeats work
The textbook Fibonacci function is short and correct, and wildly wasteful:
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
We counted the calls it makes:
| n | fib(n) | Function calls made |
|---|---|---|
| 10 | 55 | 177 |
| 20 | 6,765 | 21,891 |
| 30 | 832,040 | 2,692,537 |
Each step up by 10 multiplies the work by more than 100, because fib(28) is computed once for fib(30)'s first branch and again inside fib(29), and the same duplication repeats all the way down. This is exponential growth; see big O notation explained for what that means at scale.
The fix is memoization: remember each result the first time it's computed. Python's standard library does it with one decorator:
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
With the cache, fib(30) returned the same 832,040 after only 31 calls to the function body, one for each value from 0 to 30. The Python documentation describes functools.cache (Python 3.9+) as the same as lru_cache(maxsize=None), smaller and faster because it never evicts entries. Note that memoization fixes the repeated work but not the depth: a cold call to fib(5000) still recurses 5,000 levels deep.
Recursion vs a loop
Anything written recursively can be written with a loop, sometimes with an explicit stack. The iterative Fibonacci uses constant memory and has no depth limit:
def fib_iter(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
| Recursion | Loop | |
|---|---|---|
| Fits naturally | Trees, nested data, divide-and-conquer (merge sort, quicksort), parsing | Sequences, counters, anything linear |
| Depth limit in Python | About 1,000 by default | None |
| Memory | One stack frame per active call | Usually constant |
| Readability | Often shorter for tree-shaped problems | Often clearer for linear ones |
A practical rule for Python: use recursion when the depth is bounded by something small, like the nesting of a folder tree or a JSON document, or log₂ n in a divide-and-conquer algorithm. Use a loop when the depth grows with the size of the input, such as walking a list one item at a time.
A recursive function that's worth writing
Summing every number in an arbitrarily nested list is awkward with loops and natural with recursion, because the data itself is recursive:
def nested_sum(items):
total = 0
for item in items:
if isinstance(item, list):
total += nested_sum(item) # recursive step: a smaller list
else:
total += item # base case: a plain number
return total
print(nested_sum([1, [2, 3], [4, [5, 6]], 7])) # 28
The depth here equals the nesting depth of the data (three levels), not the number of items, so it stays far from the limit for any realistic input.
How to write a recursive function
- Write the base case first. What input is so small you know the answer immediately? An empty list, 0, 1, a leaf node.
- Assume the recursive call works on a smaller input, and ask only: how do I build the answer for this input from that?
- Check that every path shrinks towards the base case, including negative numbers and empty inputs.
- Check the depth. If it can exceed a few hundred, plan for a loop.
Frequently asked questions
- What is a base case in recursion?
- The base case is the input for which the function returns an answer directly, without calling itself again. For factorial it is n <= 1, which returns 1. Without a reachable base case the function keeps calling itself until the language's stack limit stops it.
- Is recursion slower than a loop?
- In Python, usually yes, because every call creates a new stack frame. In our test on Python 3.12, summing 0 to 500 recursively took about 36 microseconds against about 12 for a for loop. Depth is also limited to about 1,000 calls by default. The bigger performance problem is repeated work, as in naive Fibonacci, which memoization or an iterative rewrite fixes.
- Should I just raise the recursion limit with sys.setrecursionlimit?
- Only if you know the recursion is correct and genuinely needs to go deeper, and you raise it moderately. Python's documentation warns that a too-high limit can crash the interpreter, because the limit exists to stop the C stack from overflowing. If the depth grows with input size, rewriting the function as a loop is the safer fix.
- Does Python optimize tail recursion?
- No. A function whose last action is calling itself still uses one stack frame per call in CPython. The countdown example in this article is tail-recursive and still hits RecursionError past the limit, so deep tail recursion should be written as a loop.