Python Recursion
What you will learn
- What recursion is: a function that calls itself
- The two parts: the base case and the recursive case
- How the call stack works, and the recursion limit
- Classic examples, including trees and nested data
- Why naive Fibonacci is slow, and how memoisation fixes it
- When to use a loop instead
1. A function that calls itself
A function can call itself. This is called recursion. It is natural for problems that contain smaller copies of themselves: a countdown from 5 is "say 5, then count down from 4".
def countdown(n):
if n == 0:
print("liftoff")
return
print(n)
countdown(n - 1)
countdown(3)
3
2
1
liftoff
Every recursive function needs two parts:
| Part | Job | In countdown |
|---|---|---|
| base case | the simplest input, answered directly, with no further call | n == 0 |
| recursive case | handle one step, then call itself on a smaller problem | print(n) and countdown(n - 1) |
If the base case is missing, or the problem never gets smaller, the function calls itself forever (section 4).
Quick check: what is the base case of `countdown`?
n == 0: it prints liftoff and stops, without calling itself.
2. Factorial
The factorial of n, written n!, is n × (n-1) × ... × 1, with 0! = 1. It is defined in terms of itself: n! = n × (n-1)!.
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(0), factorial(1), factorial(5), factorial(10))
1 1 120 3628800
You can follow the calls by printing with an indent for each level of depth:
def trace(n, depth=0):
print(" " * depth + f"factorial({n})")
if n <= 1:
print(" " * depth + "-> 1")
return 1
r = n * trace(n - 1, depth + 1)
print(" " * depth + f"-> {r}")
return r
trace(3)
factorial(3)
factorial(2)
factorial(1)
-> 1
-> 2
-> 6
The calls go down to the base case, and then the answers come back up: factorial(1) returns 1, so factorial(2) returns 2 * 1, so factorial(3) returns 3 * 2.
3. The call stack
Each call to a function is kept by Python in a stack of calls, one frame per call. A frame holds that call's own parameters and local variables (lesson 11.5). While factorial(3) waits for factorial(2), its frame stays on the stack. The deepest call finishes first, and the stack unwinds (the stack idea is lesson 7.6).
This is why each level of recursion has its own n: they do not interfere.
4. The recursion limit
The stack has a maximum depth. Python's default is 1000 calls:
import sys
print(sys.getrecursionlimit())
1000
Going deeper raises a RecursionError:
def depth(n):
return 0 if n == 0 else 1 + depth(n - 1)
print(depth(500), depth(900))
depth(5000)
500 900
RecursionError: maximum recursion depth exceeded
A function with no base case hits the same wall:
def missing_base(n):
return n * missing_base(n - 1)
Calling missing_base(3) raises RecursionError, because n goes 3, 2, 1, 0, -1, ... forever. Two lessons: always make sure the base case can be reached, and for very deep problems prefer a loop (section 9). Python does not optimise "tail" calls, so even a function that returns the recursive call directly uses a new frame each time. You can raise the limit with sys.setrecursionlimit(n), but a bigger limit risks crashing the program, so use it with care.
5. Recursion on sequences
Sequences are naturally recursive: the first item plus the rest.
def rec_sum(nums):
if not nums:
return 0
return nums[0] + rec_sum(nums[1:])
def reverse(s):
return s if len(s) <= 1 else reverse(s[1:]) + s[0]
def is_pal(s):
return len(s) < 2 or (s[0] == s[-1] and is_pal(s[1:-1]))
print(rec_sum([1, 2, 3, 4]), rec_sum([]))
print(reverse("hello"), is_pal("madam"), is_pal("abca"))
10 0
olleh True False
rec_sum: the sum of a list is its first item plus the sum of the rest. The base case is the empty list, with sum0.reverse: reverse the rest, then add the first letter at the end.is_pal: a text is a palindrome if the ends match and the middle is a palindrome. Texts of 0 or 1 characters are palindromes.
Each slice makes a copy, so these are teaching examples. In real code, use sum(nums), s[::-1] and a comparison.
6. Dividing the problem: power and gcd
Sometimes the recursion halves the problem, which makes it very fast:
def power(b, e):
if e == 0:
return 1
half = power(b, e // 2)
return half * half if e % 2 == 0 else half * half * b
def gcd(a, b):
return a if b == 0 else gcd(b, a % b)
print(power(2, 10), power(3, 5))
print(gcd(48, 18), gcd(7, 5))
1024 243
6 1
power needs only about log2(e) calls, not e of them: 2 ** 1000 takes about ten levels. gcd is the Euclid method from lesson 6.1, written recursively.
7. Two recursive calls: Fibonacci
The Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, ...: each is the sum of the two before it:
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print([fib(i) for i in range(10)])
print(fib(20))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
6765
It is beautiful, and it is very slow, because each call makes two more, and the same values are worked out again and again. Counting the calls:
calls = 0
def fib_counted(n):
global calls
calls += 1
return n if n < 2 else fib_counted(n - 1) + fib_counted(n - 2)
fib_counted(20)
print(calls)
21891
21,891 calls to find fib(20), and the number roughly multiplies by 1.6 for each step further. fib(50) would take a very long time.
Memoisation
Memoisation means remembering answers you have already worked out. The standard library does it for you with the lru_cache decorator (decorators are lesson 11.11):
from functools import lru_cache
calls = 0
@lru_cache(maxsize=None)
def fib_fast(n):
global calls
calls += 1
return n if n < 2 else fib_fast(n - 1) + fib_fast(n - 2)
print(fib_fast(20), calls)
print(fib_fast(90))
6765 21
2880067194370816120
Only 21 real calls were needed for fib(20), one per different value, and fib(90) is instant. You can also keep the answers yourself in a dictionary:
def memo_fib(n, memo={}):
if n < 2:
return n
if n not in memo:
memo[n] = memo_fib(n - 1) + memo_fib(n - 2)
return memo[n]
print(memo_fib(50))
12586269025
(Here a mutable default is used on purpose as a cache. Lesson 11.9 explains the usual danger.)
8. Recursion on nested and branching data
Recursion shines when data is nested to unknown depth, such as lists inside lists, folders in folders, or a tree:
def flatten(x):
out = []
for item in x:
out.extend(flatten(item) if isinstance(item, list) else [item])
return out
print(flatten([1, [2, [3, [4, 5]], 6]]))
[1, 2, 3, 4, 5, 6]
A tree of dictionaries, where each node has a name and a list of children:
tree = {"name": "root", "children": [
{"name": "a", "children": [{"name": "a1", "children": []}]},
{"name": "b", "children": []},
]}
def names(node):
out = [node["name"]]
for child in node["children"]:
out += names(child)
return out
def height(node):
return 1 + max((height(c) for c in node["children"]), default=0)
print(names(tree))
print(height(tree))
['root', 'a', 'a1', 'b']
3
The base case is hidden: a node with no children simply runs the loop zero times. File systems, web pages, menus and family trees all have this shape.
Making choices: permutations and Towers of Hanoi
Recursion can also try all choices. This builds every ordering of a list:
def perms(items):
if len(items) <= 1:
return [items]
out = []
for i, x in enumerate(items):
for p in perms(items[:i] + items[i + 1:]):
out.append([x] + p)
return out
print(perms([1, 2, 3]))
print(len(perms([1, 2, 3, 4])))
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
24
The Towers of Hanoi puzzle moves n discs from peg A to peg C, using B, one disc at a time, never putting a bigger disc on a smaller one. The recursive idea is: move n-1 discs out of the way, move the biggest, then move the n-1 back on top:
def hanoi(n, a, b, c, moves):
if n == 0:
return
hanoi(n - 1, a, c, b, moves)
moves.append((a, c))
hanoi(n - 1, b, a, c, moves)
moves = []
hanoi(3, "A", "B", "C", moves)
print(len(moves))
print(moves)
7
[('A', 'C'), ('A', 'B'), ('C', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('A', 'C')]
Three discs need 7 moves, and n discs need 2 ** n - 1. Writing this with a loop would be much harder.
9. Recursion or a loop?
| Recursion | Loop | |
|---|---|---|
| nested or branching data (trees, nested lists) | natural | needs a stack by hand |
| "divide in halves" problems | natural | possible |
| long, straight repetition (add 1 million numbers) | risk of RecursionError, slower |
best |
| memory | one frame per call | constant |
| clarity | great when the problem is recursive | great when it is a plain repeat |
Rules of thumb:
- If a loop does the job simply, use a loop.
- If the data or problem is self-similar, use recursion.
- Always check the base case and that each call makes the problem smaller.
- If the same sub-problem repeats, add memoisation.
Worked example: the size of a nested folder
Each folder is a dictionary of names. A file is a number (its size in KB), and a folder is another dictionary. Find the total size, and the number of files.
folder = {
"notes.txt": 4,
"photos": {"a.jpg": 120, "b.jpg": 95, "old": {"c.jpg": 80}},
"docs": {"cv.pdf": 30, "letter.docx": 12},
}
def total_size(item):
if isinstance(item, dict):
return sum(total_size(child) for child in item.values())
return item
def file_count(item):
if isinstance(item, dict):
return sum(file_count(child) for child in item.values())
return 1
print(total_size(folder))
print(file_count(folder))
print(total_size(folder["photos"]))
341
6
295
| Case | What the function does |
|---|---|
| a file (a number) | base case: its size is the number itself (or 1 for the count) |
| a folder (a dictionary) | recursive case: add up the results for each child |
Folders may be nested to any depth, and the same short function handles them all. The names and sizes are made up.
Common mistakes
- No base case, or a base case that is never reached:
RecursionError. - A recursive call that does not make the problem smaller.
- Using recursion for long straight repetition instead of a loop.
- Repeating the same sub-problem (naive Fibonacci) without memoisation.
- Forgetting to
returnthe recursive result. Withoutreturn, the answer is lost and you getNone. - Raising the recursion limit instead of fixing the design.
Key takeaways
- A recursive function has a base case (answered directly) and a recursive case (a smaller version of the same problem).
- Each call has its own frame on the call stack; Python's default limit is about 1000 calls, then
RecursionError. - Recursion suits self-similar data and divide-and-conquer: nested lists, trees, folders, permutations, halving.
- Overlapping sub-problems need memoisation:
@lru_cacheor a dictionary. - Use a loop for plain repetition; always check that the base case can be reached.
Practice
1. Write a recursive sum_to(n) that returns 1 + 2 + ... + n.
Show answer
def sum_to(n):
if n <= 0:
return 0
return n + sum_to(n - 1)
2. What is wrong with def f(n): return f(n - 1)?
Show answer
There is no base case, so it calls itself forever until Python raises RecursionError.
3. Write a recursive function digits_sum(n) that adds the digits of a whole number.
Show answer
def digits_sum(n):
return n if n < 10 else n % 10 + digits_sum(n // 10)
digits_sum(12345) gives 15.
4. Why is fib(40) slow with the simple version?
Show answer
Each call makes two more calls, and the same values are recalculated many times, so the number of calls grows very fast. Memoisation stores each answer once.
5. Write a recursive function that counts the items in a nested list such as [1, [2, [3]]].
Show answer
def count_items(x):
return sum(count_items(i) if isinstance(i, list) else 1 for i in x)
For [1, [2, [3]]] it returns 3.
6. When is a loop better than recursion?
Show answer
For long, straight repetition (such as adding a million numbers), where a loop uses less memory, is faster, and cannot hit the recursion limit.