Recursion Explained: Base Cases, the Call Stack and Limits
A recursive function solves a problem by calling itself on a smaller version of the same problem. That sounds circular, and it would be, except for one rule: some inputs are small enough to answer directly, without another call. This guide covers the two parts every recursive function needs, how the call stack makes recursion work, what Python does when recursion goes too deep, how to turn a recursion into a loop, and when recursion is the natural tool.
Base case and recursive case
Every correct recursive function has:
- a base case: an input it answers directly, without recursing;
- a recursive case: for every other input, a call on a smaller input, combined with a little extra work.
"Smaller" is the important word. Each recursive call must move closer to a base case, so that every chain of calls eventually ends. For factorial, n! = n x (n - 1)! with base case 1! = 1 (and 0! = 1). For the sum of a list, the sum of an empty list is 0, and the sum of any other list is its first item plus the sum of the rest.
When you write a recursive function, trust the recursive call. Assume factorial(n - 1) returns the right answer, and check only two things: that the base case is right, and that the recursive case builds the right answer from a correct smaller one. That is the same reasoning as a proof by induction.
Tracing factorial on the call stack
Examples use Python 3.10 or later and only the standard library. This version of factorial prints a line when each call starts and when it returns, indented by depth.
def factorial(n, depth=0):
indent = " " * depth
print(f"{indent}factorial({n}) called")
if n <= 1:
result = 1
else:
result = n * factorial(n - 1, depth + 1)
print(f"{indent}factorial({n}) returns {result}")
return result
factorial(4)
Output:
factorial(4) called
factorial(3) called
factorial(2) called
factorial(1) called
factorial(1) returns 1
factorial(2) returns 2
factorial(3) returns 6
factorial(4) returns 24
Read it from the first line down. factorial(4) cannot finish until factorial(3) returns, which waits for factorial(2), which waits for factorial(1). Each waiting call is a frame on the call stack, holding its own value of n and the point where it will resume. When the base case returns 1, the frames finish in reverse order: 2 x 1 = 2, 3 x 2 = 6, 4 x 6 = 24. Four calls, four frames at the deepest point. That depth is why recursion uses O(n) space here, even though each frame is small.
The sum of a list unwinds the same way. total([3, 1, 4]) becomes 3 + total([1, 4]), then 3 + (1 + total([4])), then 3 + (1 + (4 + total([]))). The base case returns 0 and the additions happen on the way back up: 4, then 5, then 8.
What happens without a base case
import sys
def total(items):
if not items:
return 0
return items[0] + total(items[1:])
def total_no_base(items):
return items[0] + total_no_base(items[1:])
def count_down_no_base(n):
return count_down_no_base(n - 1)
print(total([3, 1, 4, 1, 5]))
print(sys.getrecursionlimit())
try:
total_no_base([3, 1, 4])
except IndexError as err:
print("IndexError:", err)
try:
count_down_no_base(5)
except RecursionError as err:
print("RecursionError:", err)
Output:
14
1000
IndexError: list index out of range
RecursionError: maximum recursion depth exceeded
The version with a base case returns 14. Remove the base case and one of two things happens. If the input runs out first, you get an ordinary error: total_no_base eventually calls itself on an empty list and items[0] raises IndexError. If nothing stops it, the function recurses until Python refuses to go deeper and raises RecursionError. The same error appears when a base case exists but is unreachable, for example if n == 0 on a function called with a negative or fractional n that steps down by 1.
A side note on cost: items[1:] copies the rest of the list at every level, so total as written does O(n^2) work in total. It is fine for tracing; for real code, pass an index or use a loop.
Python's recursion limit
CPython caps the depth of the call stack to protect itself from crashing. sys.getrecursionlimit() reports the cap, which is 1000 by default (the run above prints it). Going past it raises RecursionError: maximum recursion depth exceeded. The sys module documentation describes the limit.
Python also does not perform tail-call elimination. In some languages, a call that is the very last thing a function does (a tail call) reuses the current frame, so a tail-recursive function runs in constant stack space. In Python every call gets a new frame, tail call or not. A recursion n levels deep needs n frames, so any algorithm whose depth grows with the input (one level per list item, say) will fail on large inputs.
You will see advice to raise the limit with sys.setrecursionlimit. Do not treat that as a fix. The limit exists because the real stack is finite, and raising it too far can crash the interpreter outright instead of raising a catchable error. If the depth can grow with n, rewrite the function as a loop.
Converting recursion to a loop
When each call makes at most one recursive call and does nothing after it returns except pass the result along, the conversion is mechanical: keep the changing arguments in variables and loop until the base case.
def total_loop(items):
result = 0
for x in items:
result += x
return result
def count_down(n):
if n == 0:
return "done"
return count_down(n - 1)
def count_down_loop(n):
while n != 0:
n -= 1
return "done"
print(total_loop(list(range(2000))))
print(count_down_loop(100000))
try:
print(count_down(100000))
except RecursionError as err:
print("RecursionError:", err)
Output:
1999000
done
RecursionError: maximum recursion depth exceeded
Both loops handle inputs the recursion cannot. count_down is tail-recursive, yet at a depth of 100,000 it still fails, which is the missing tail-call elimination in action.
When a function makes several recursive calls, or does work after they return, replace the call stack with an explicit stack of your own. This example sums a list of arbitrarily nested lists both ways:
def nested_sum(value):
if isinstance(value, int):
return value
return sum(nested_sum(item) for item in value)
def nested_sum_stack(value):
result = 0
stack = [value]
while stack:
current = stack.pop()
if isinstance(current, int):
result += current
else:
stack.extend(current)
return result
data = [1, [2, 3], [[4], 5, [6, [7, 8]]], 9]
print(nested_sum(data), nested_sum_stack(data))
Output:
45 45
The explicit-stack version visits items in a different order, but the sum is the same, and its depth is limited only by memory, not by the recursion limit.
When recursion is the natural fit
- Recursive data. Trees, nested lists and file systems are defined in terms of smaller copies of themselves, so code that mirrors the definition is short and easy to check. The depth is the height of the structure, often small.
- Divide and conquer. Merge sort and binary search split the input into parts and solve each part the same way. Their depth is O(log n), far below the limit. Their running times are found by writing a recurrence, the subject of the recurrence relations guide.
- Exhaustive search. Generating subsets, permutations or board placements is a tree of choices; backtracking walks that tree with recursion.
Recursion is a poor fit when the depth is proportional to a large n, as in summing a long list one item per call.
How to trace and debug a recursive function
- Test the base case alone first:
factorial(1),total([]). - Test the smallest input that recurses once, then twice.
- Add an indented print at entry and exit, as in the factorial trace, to see the order of calls.
- Check that every recursive call's argument is strictly smaller in some measure (length, value, size) and can actually reach the base case.
- Count calls with a counter when performance is surprising.
When recursion repeats itself: naive Fibonacci
Step 5 matters more than it looks. The textbook Fibonacci function makes two recursive calls, and they overlap: fib(n - 1) recomputes fib(n - 2) from scratch.
calls = 0
def fib(n):
global calls
calls += 1
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
for n in [10, 20, 25]:
calls = 0
value = fib(n)
print(n, value, calls)
Output (n, fib(n), number of calls):
10 55 177
20 6765 21891
25 75025 242785
fib(20) makes 21,891 calls to compute 6,765, and fib(25) makes 242,785. The call count grows exponentially, while the depth stays only n, so this function is slow without ever hitting the recursion limit. The fix is to remember each answer the first time it is computed, which turns the running time into O(n). That idea, applied systematically, is dynamic programming.
Check yourself
- What is the maximum stack depth of
factorial(n)? (n frames.) - A recursive function with a correct base case raises
RecursionErroron a large input. What is the fix? (Rewrite it as a loop, or with an explicit stack.)