Introduction & Syntax
Recursion · Study material
A recursive function solves a problem by calling itself on a smaller version of the same problem, until it reaches a case simple enough to answer directly. Recursion is the natural way to handle nested data (folders, JSON, trees), divide-and-conquer algorithms (binary search, merge sort) and backtracking (permutations, puzzles). It is also a favourite of written tests – "what does this recursive function print?" – and of interviews. This topic explains base cases, the call stack, memoisation and the recursion limit, then gives you 50 practice questions run on Python 3.
On this page
- Base case and recursive case
- How the call stack goes down and comes back
- Classic recursive functions
- Tree recursion, memoisation and lru_cache
- Recursion on nested data; divide and conquer; backtracking
- RecursionError, the recursion limit and iteration
Base case and recursive case
Every recursive function needs two parts: a base case that returns an answer without recursing, and a recursive case that calls the function on a smaller input and combines the result. Each call must move closer to the base case; otherwise the recursion never ends and Python raises RecursionError.
def factorial(n):
if n <= 1: # base case: answer known, no further calls
return 1
return n * factorial(n - 1) # recursive case: a SMALLER version of the same problem
def total(nums):
if not nums: # base case: empty list
return 0
return nums[0] + total(nums[1:])
print(factorial(5), factorial(1), factorial(20))
print(total([4, 8, 15, 16, 23, 42]))
120 1 2432902008176640000 108
The call stack: going down and coming back
Each call gets its own frame with its own local variables, stacked on top of the caller. Code before the recursive call runs on the way down (in call order); code after it runs on the way back up (in reverse order). This one idea answers most "predict the output" recursion questions.
def trace(n, depth=0):
pad = " " * depth
if n == 0:
print(pad + "base case reached")
return 1
print(pad + f"going down: n={n}") # runs BEFORE the recursive call
result = n * trace(n - 1, depth + 1)
print(pad + f"coming back: n={n} -> {result}") # runs AFTER it returns
return result
trace(3)
going down: n=3
going down: n=2
going down: n=1
base case reached
coming back: n=1 -> 1
coming back: n=2 -> 2
coming back: n=3 -> 6Classic recursive functions
Many problems shrink naturally: n! = n × (n−1)!, the digits of n are its last digit plus the digits of n // 10, a string reversed is its tail reversed plus its first character, and gcd(a, b) = gcd(b, a % b). Halving the exponent makes power take only log₂(n) calls.
def power(base, exp): # fast power: halve the exponent each time
if exp == 0:
return 1
half = power(base, exp // 2)
return half * half * (base if exp % 2 else 1)
def digit_sum(n):
return n if n < 10 else n % 10 + digit_sum(n // 10)
def reverse(s):
return s if len(s) <= 1 else reverse(s[1:]) + s[0]
def gcd(a, b):
return a if b == 0 else gcd(b, a % b)
def to_binary(n):
return str(n) if n < 2 else to_binary(n // 2) + str(n % 2)
print(power(2, 30), digit_sum(98765), reverse("python"), gcd(84, 36), to_binary(37))
1073741824 35 nohtyp 12 100101
Tree recursion and memoisation
When a function calls itself more than once, the calls form a tree and repeated sub-problems explode: naive fib(20) makes 21,891 calls. Memoisation stores each result the first time it is computed. @functools.lru_cache (or @functools.cache) adds it in one line – the arguments must be hashable.
from functools import lru_cache
calls = 0
def fib(n): # tree recursion: two calls per call
global calls
calls += 1
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(20), "computed with", calls, "calls")
@lru_cache(maxsize=None) # remember every result: each n computed once
def fib_fast(n):
return n if n < 2 else fib_fast(n - 1) + fib_fast(n - 2)
print(fib_fast(90))
print(fib_fast.cache_info().misses, "distinct calls")
6765 computed with 21891 calls 2880067194370816120 91 distinct calls
Recursion on nested data
Data that contains smaller data of the same shape – nested lists, folder trees, JSON – is processed most naturally by recursion: handle a plain item directly, and recurse into each container.
def deep_sum(item):
if isinstance(item, list):
return sum(deep_sum(x) for x in item) # recurse into every sub-list
return item
def depth(item):
if not isinstance(item, list):
return 0
return 1 + max((depth(x) for x in item), default=0)
data = [1, [2, [3, 4], 5], [[6]], []]
print(deep_sum(data), depth(data))
folders = {"src": {"app": {"main.py": 120, "util.py": 40}, "README.md": 8}, "setup.py": 12}
def size(tree):
return sum(size(v) if isinstance(v, dict) else v for v in tree.values())
print("Total size:", size(folders))
21 3 Total size: 180
Divide and conquer
Split the problem in halves, solve each half recursively and combine: binary search discards half the list at every step (O(log n)), and merge sort sorts two halves and merges them (O(n log n)).
def binary_search(items, target, lo=0, hi=None):
if hi is None:
hi = len(items) - 1
if lo > hi:
return -1 # not found
mid = (lo + hi) // 2
if items[mid] == target:
return mid
if items[mid] < target:
return binary_search(items, target, mid + 1, hi)
return binary_search(items, target, lo, mid - 1)
def merge_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
left, right = merge_sort(a[:mid]), merge_sort(a[mid:])
out = []
while left and right:
out.append(left.pop(0) if left[0] <= right[0] else right.pop(0))
return out + left + right
nums = [3, 9, 14, 21, 30, 42, 57]
print(binary_search(nums, 30), binary_search(nums, 5))
print(merge_sort([38, 27, 43, 3, 9, 82, 10]))
4 -1 [3, 9, 10, 27, 38, 43, 82]
Backtracking
Backtracking builds solutions step by step and explores every choice: to list permutations, fix each character in turn and permute the rest; to list subsets, take every subset of the rest with and without the first item.
def permutations(s):
if len(s) <= 1:
return [s]
result = []
for i, ch in enumerate(s):
for rest in permutations(s[:i] + s[i + 1:]): # fix one char, permute the rest
result.append(ch + rest)
return result
def subsets(items):
if not items:
return [[]]
smaller = subsets(items[1:])
return smaller + [[items[0]] + s for s in smaller] # without / with the first item
print(permutations("abc"))
print(subsets([1, 2, 3]))
['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]
Common mistakes
- No base case, or one that is never reached – RecursionError.
- Forgetting return before the recursive call – the result is lost and None comes back.
- A wrong base value – factorial(0) returning 0 makes every result 0.
- Naive tree recursion on big inputs – exponential time; memoise.
- Very deep recursion – Python's limit is about 1000 frames; use a loop.
- lru_cache with list arguments – unhashable; pass tuples.
Key points to remember
- Every recursion needs a base case and progress towards it.
- Code before the call runs going down; code after it runs coming back.
- Each call has its own local variables.
- Tree recursion repeats work; memoise with lru_cache.
- The default recursion limit is about 1000; Python has no tail-call optimisation.
- Recursion suits nested data, divide and conquer and backtracking.
Frequently asked questions
Is recursion slower than a loop in Python?
Usually a little, because each call creates a frame. Choose recursion when it makes the code clearer – trees, nested data, backtracking – and loops for simple repetition.
Can I raise the recursion limit?
sys.setrecursionlimit() can raise it, but very deep recursion can still exhaust the C stack and crash the interpreter. Rewriting the function iteratively is safer.
Does Python optimise tail recursion?
No. A recursive call in tail position still uses a new frame.
Where can I learn more?
Read Scope, Lambda and Recursion in the Python tutorial and the Functions topic, then practise with the exercises below.