Skip to main content
Albero Academy

Recursion

Functions that call themselves — elegant for problems with self-similar structure.

Functions10 min

Recursion is when a function calls itself to solve a smaller version of the same problem, until it reaches a simple case it can answer directly. It's a natural fit for anything with self-similar structure — trees, nested data, divide-and-conquer.

The two parts

Every recursive function needs a base case (when to stop) and a recursive case (call itself on something smaller):

factorial
def factorial(n):
if n <= 1: # BASE CASE — stops the recursion
return 1
return n * factorial(n - 1) # RECURSIVE CASE — smaller subproblem
factorial(5) # 5 * 4 * 3 * 2 * 1 = 120

Trace it: factorial(3) → 3 * factorial(2) → 3 * 2 * factorial(1) → 3 * 2 * 1 = 6. Each call waits for the smaller one to finish.

Where recursion shines

Recursion is elegant for nested/tree-shaped data where a loop would be awkward:

summing a nested list
def deep_sum(items):
total = 0
for x in items:
if isinstance(x, list):
total += deep_sum(x) # recurse into sub-lists
else:
total += x
return total
deep_sum([1, [2, 3, [4, 5]], 6]) # 21

Base case & limits

Key takeaways

  1. 01A recursive function calls itself on a smaller subproblem.
  2. 02It needs a base case (to stop) and a recursive case (to shrink the problem).
  3. 03It shines on trees, nested structures and divide-and-conquer.
  4. 04Missing/unreachable base case → infinite recursion → RecursionError.
  5. 05For simple/flat iteration, a loop is often clearer and faster.

Finished this chapter?

Mark it complete to track your progress through Python.