Module 9 · Functions — topic 17 of 19
Recursion
Functions that call themselves: base cases, recursive cases, how the call stack unwinds, Python's recursion limit, memoisation with functools.lru_cache, and recursion on nested data.
Learning objectives
- Write recursive functions with correct base cases
- Trace recursive calls and their returns
- Speed up overlapping recursion with lru_cache
Definition
Recursion is a technique where a function solves a problem by calling itself on a smaller version of the same problem, until it reaches a base case that can be answered directly.
Introduction
The factorial of 5 is 5 × the factorial of 4. A folder's size is the size of its files plus the sizes of its sub-folders. Definitions like these are recursive, and Python can express them directly.
Why it matters
Recursion is the natural tool for nested structures — directory trees, JSON, organisation charts — and for divide-and-conquer algorithms such as binary search and merge sort.
Detailed explanation
Every recursive function needs a base case that returns without recursing, and a recursive case that calls the function on a smaller input, moving towards the base case.
Each call has its own local variables on the call stack. When the base case returns, the calls finish one by one in reverse order.
Python limits recursion depth (about 1000 by default) and raises RecursionError beyond it. Python doesn't optimise tail calls, so very deep recursion should be rewritten as a loop.
Naive recursion can repeat work enormously (Fibonacci). @functools.lru_cache remembers results for arguments it has seen, turning exponential time into linear time.
Recursion shines on nested data: a function that handles a list by calling itself on any inner lists processes data of any depth.
Syntax
- Write the base case first.
- Each call must move closer to it.
- Deep recursion raises RecursionError.
Code examples
Factorial and sum of digits
120 2432902008176640000 35
Tracing the stack
call 2
call 1
call 0
return 0
return 1
return 3More examples
Memoisation and nested data
6765 21891 2880067194370816120 410
Step-by-step explanation
- fib recomputes the same values over and over: 21,891 calls for fib(20).
- @lru_cache stores each result, so fast_fib(90) needs only about 90 distinct calls.
- total_size treats an int as a file size (base case) and a list as a folder, summing its children recursively.
- The nested folder structure of any depth totals 120 + 30 + 45 + 10 + 5 + 200 = 410.
Expected output
Running “Memoisation and nested data” prints exactly:
Practical applications
- Walking directory trees and nested JSON.
- Parsing expressions and evaluating syntax trees.
- Backtracking solvers for puzzles and permutations.
Best practices
- Write the base case first.
- Use lru_cache when the same arguments recur.
- Use a loop when depth could be in the thousands.
Common mistakes
Missing base case
Avoid
Prefer
Without a base case the recursion never stops: RecursionError.
Not moving towards the base case
Avoid
Prefer
Each call must shrink the problem.
Important notes
- sys.getrecursionlimit() shows the limit; raising it is rarely a good fix.
Key takeaways
- A recursive function needs a base case and progress towards it.
- Calls unwind in reverse order on the stack.
- lru_cache removes repeated work; loops avoid RecursionError.
Try it yourself
- 1Write a recursive function that reverses a string.
- 2Write flatten(nested) that turns [1, [2, [3, 4]], 5] into [1, 2, 3, 4, 5].
Finished reading? Mark it complete to update your dashboard.
Suggested practice
2 questions test this exact topic. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?
- ModerateWhat is printed?