Recursion
Recursion is a function calling itself on a smaller input until it hits a base case. Trees, divide-and-conquer, and backtracking are naturally recursive; Python's call stack is finite.
Detailed Explanation
A recursive function has two parts. The base case returns without calling itself. The recursive case calls itself on a strictly smaller problem and combines the results. factorial(n) is 1 when n <= 1, otherwise n * factorial(n - 1). Miss the base case and the function recurses until RecursionError.
Each call uses a stack frame: locals, return address, and bookkeeping. CPython's default limit is 1000 frames (sys.getrecursionlimit()). A linear recursion of n=10⁵ will not finish. You raise the limit only when you trust the depth and the platform. Prefer an explicit stack or an iterative rewrite for deep linear chains.
Tail-call elimination would reuse a frame when the recursive call is the last action. CPython does not do this. return factorial(n - 1) still consumes a frame. Write a loop if you wanted a tail call.
Slicing in the recursive call is a common hidden cost. walk(items[1:]) copies the list every time, so a "linear" function is O(n²) time and space. Pass an index: walk(items, i + 1).
Mutual recursion (A calls B calls A) is still recursion. Tree recursion (two calls per frame, as in naive Fibonacci) can be exponential time. Memoisation or an explicit table turns that into dynamic programming.
Use recursion when the data is recursive: trees, nested JSON, the call graph of a parser. Use a loop when the data is a flat list. Both can be correct; the stack budget and the constant overhead decide.
Code Examples
def factorial(n: int) -> int:
if n < 0:
raise ValueError("n must be >= 0")
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120# Index, not slice: O(n) time and O(n) stack, not O(n²) copies.
def total(items: list[int], i: int = 0) -> int:
if i == len(items):
return 0
return items[i] + total(items, i + 1)
print(total([10, 20, 30])) # 60# Explicit stack for a deep tree walk.
def walk(root: dict) -> list[str]:
names = []
stack = [root]
while stack:
node = stack.pop()
names.append(node["name"])
stack.extend(reversed(node.get("children", [])))
return namesCommon Gotchas
No base case, or a case that does not shrink
`RecursionError` or an infinite loop of calls.
CPython has no tail-call optimisation
a tail recursive function still dies at ~1000 frames.
`RecursionError` is a `RuntimeError` subclass
catching `Exception` in a framework will catch it. Do not hide it.