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):
def factorial(n):if n <= 1: # BASE CASE — stops the recursionreturn 1return n * factorial(n - 1) # RECURSIVE CASE — smaller subproblemfactorial(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:
def deep_sum(items):total = 0for x in items:if isinstance(x, list):total += deep_sum(x) # recurse into sub-listselse:total += xreturn totaldeep_sum([1, [2, 3, [4, 5]], 6]) # 21
Base case & limits
Key takeaways
- 01A recursive function calls itself on a smaller subproblem.
- 02It needs a base case (to stop) and a recursive case (to shrink the problem).
- 03It shines on trees, nested structures and divide-and-conquer.
- 04Missing/unreachable base case → infinite recursion → RecursionError.
- 05For simple/flat iteration, a loop is often clearer and faster.
