Skip to content

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.

Beginner 15 min read·Lesson 142 of 306 in Python Programming

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

Python
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1) # recursive case
  • Write the base case first.
  • Each call must move closer to it.
  • Deep recursion raises RecursionError.

Code examples

Factorial and sum of digits

Python
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
def digit_sum(n):
return n if n < 10 else n % 10 + digit_sum(n // 10)
print(factorial(5), factorial(20))
print(digit_sum(98765))
Output
120 2432902008176640000
35

Tracing the stack

Python
def countdown(n, depth=0):
pad = " " * depth
print(pad + f"call {n}")
result = 0 if n == 0 else n + countdown(n - 1, depth + 1)
print(pad + f"return {result}")
return result
countdown(2)
Output
call 2
  call 1
    call 0
    return 0
  return 1
return 3

More examples

Memoisation and nested data

Python
from functools import lru_cache
calls = 0
def fib(n):
global calls
calls += 1
return n if n < 2 else fib(n - 1) + fib(n - 2)
@lru_cache(maxsize=None)
def fast_fib(n):
return n if n < 2 else fast_fib(n - 1) + fast_fib(n - 2)
print(fib(20), calls)
print(fast_fib(90))
def total_size(item):
if isinstance(item, int):
return item
return sum(total_size(child) for child in item)
folder = [120, [30, 45, [10, 5]], 200, []]
print(total_size(folder))
Output
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:

TextOutput
6765 21891
2880067194370816120
410

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

def f(n):
return n + f(n - 1)

Prefer

def f(n):
if n <= 0:
return 0
return n + f(n - 1)

Without a base case the recursion never stops: RecursionError.

Not moving towards the base case

Avoid

def f(n):
if n == 0:
return 0
return f(n) # same input again

Prefer

def f(n):
if n == 0:
return 0
return f(n - 1)

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

  1. 1
    Write a recursive function that reverses a string.
  2. 2
    Write 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?
Practise this topic