Thuta Learning
Python
AdvancedProgrammingBeginner

Recursion

PythonLesson 6030 min

What you'll walk away with

  • Point out the base case and the recursive case in any recursive function
  • Trace how factorial(3) goes down the call stack and comes back up
  • Explain why naive Fibonacci is slow and fix it with lru_cache
  • Walk nested data such as folders or category trees recursively
  • Rewrite deep recursion with an explicit stack to avoid RecursionError

Explain it simply

Explain it simply

Think of Russian nesting dolls. Every time you open a doll there is a smaller one inside, and you stop only when you reach the tiniest doll that does not open.

Recursion works the same way. Instead of solving a big problem directly, a function says "let me ask myself about a smaller version". The tiniest doll is the base case: its answer is known, so no further call is made. Without a base case, or if the dolls never get smaller, the opening never ends.

Problem → Why → Solution

The problem: a base case that is never reached

countdown() below has a base case, if n == 0, and countdown(3) works fine. But pass 2.5 or -1 and n never lands exactly on 0: it keeps going 1.5, 0.5, -0.5... or -2, -3...

After a moment the program stops with RecursionError: maximum recursion depth exceeded. The author felt safe because a base case existed, but never checked that every call actually reaches it.

countdown_bug.py
def countdown(n):
    if n == 0:          # base case exists ...
        print("Done!")
        return
    print(n)
    countdown(n - 1)    # ... but 2.5 or -1 skips right past 0

countdown(-1)           # RecursionError: maximum recursion depth exceeded

Why does this happen?

A base case alone is not enough; every call must also make guaranteed progress towards it. An exact check like n == 0 lets some inputs slip past. A range check such as n <= 0, or rejecting invalid input up front, is safer. Python caps the call stack, so endless recursion surfaces as RecursionError.

Core concept: recursion on the call stack

Every function call makes Python create a new stack frame holding that call's parameters and local variables. When factorial(3) calls factorial(2), the first frame is paused, waiting. Only when the base case is reached do the answers travel back up, frame by frame, completing the multiplications that were waiting.

text
factorial(3) on the call stack
------------------------------
going down (calls)                 coming back (returns)

factorial(3)  waits for 3 * ?      3 * 2 = 6   -> final answer
  factorial(2)  waits for 2 * ?    2 * 1 = 2   -> returned to (3)
    factorial(1)  base case        returns 1   -> returned to (2)

1. Base case: return the answer directly

For the smallest inputs (n <= 1, an empty list, a node with no children) return the answer without another call. Writing the base case at the top of the function makes it easy to spot.

2. Recursive case: call on a smaller problem

Call again with an input one step closer to the base case: n - 1, the rest of a list, a child node. Combine the returned answer with the current step's work, as in n * ... or size += ....

3. Watch out for repeated work

fib(n) calls fib(n-1) and fib(n-2), and both recompute the same subproblems again and again: fib(20) alone takes 21,891 calls. With @lru_cache remembering results, each n is computed only once.

4. Respect the depth limit

CPython's default recursion limit is 1000 and it does not optimise tail calls. For data that can be thousands of levels deep, such as a long linked chain, write a loop that uses a list as a stack. Raising the limit with sys.setrecursionlimit() can overflow the C stack and crash the whole process, so treat it as a last resort.

So when should you choose recursion? It is the clearest tool when the data itself is recursive, like folders inside folders or categories inside categories, and for divide-and-conquer algorithms such as merge sort or binary search that split a problem in half. For straight-line work like counting from 1 to n, a for loop is faster and simpler.

Mental model: down the stack, then back up
  1. At the base case, return directly
  2. Otherwise call with a smaller input
  3. Frames pile up on the stack
  4. Answers flow back up and combine

Trust that the recursive call already works for the smaller input and think only about the current step. This is often called the recursive leap of faith.

General pattern

python
def solve(problem):
    if is_smallest(problem):              # base case
        return direct_answer(problem)
    smaller = shrink(problem)             # must move toward the base case
    partial = solve(smaller)              # recursive case
    return combine(problem, partial)

Every recursive function has this shape: shrink() must always lead to the base case, and combine() adds the current step's work.

Example: from countdown to a folder tree

This script works through countdown, factorial and Fibonacci examples and makes each one practical. Fibonacci counts its calls and is compared with a memoized version, another example totals the size of nested folders, and the last section shows what happens past the recursion limit. factorial() also rejects negative numbers with ValueError.

recursion_demo.py
import sys
from functools import lru_cache


# ===== 1. Basic recursion: countdown =====
def countdown(n: int) -> None:
    if n == 0:                 # base case: stop here
        print("Done!")
        return
    print(n)
    countdown(n - 1)           # recursive case: a smaller problem


print("===== Countdown =====")
countdown(3)


# ===== 2. Factorial: combine results on the way back =====
def factorial(n: int) -> int:
    if n < 0:
        raise ValueError("factorial is undefined for negative numbers")
    if n <= 1:
        return 1
    return n * factorial(n - 1)


print("\n===== Factorial =====")
print(f"5! = {factorial(5)}")

# ===== 3. Fibonacci: repeated work and memoization =====
calls = 0


def fib(n: int) -> int:
    global calls
    calls += 1
    if n <= 1:
        return n
    return fib(n - 1) + fib(n - 2)


@lru_cache(maxsize=None)
def fib_memo(n: int) -> int:
    if n <= 1:
        return n
    return fib_memo(n - 1) + fib_memo(n - 2)


print("\n===== Fibonacci =====")
print(f"fib(20) = {fib(20)} using {calls} calls")
print(f"fib_memo(20) = {fib_memo(20)}, cache misses: {fib_memo.cache_info().misses}")


# ===== 4. Recursion on nested data =====
def total_size(folder: dict) -> int:
    size = sum(folder.get("files", []))
    for child in folder.get("folders", []):
        size += total_size(child)
    return size


project = {
    "files": [120, 30],
    "folders": [
        {"files": [500]},
        {"files": [10, 5], "folders": [{"files": [2000]}]},
    ],
}
print("\n===== Nested folders =====")
print(f"Total size: {total_size(project)} KB")

# ===== 5. The depth limit =====
print("\n===== Depth limit =====")
print(f"Recursion limit: {sys.getrecursionlimit()}")
try:
    factorial(5000)
except RecursionError:
    print("factorial(5000) -> RecursionError")

Code breakdown

  1. Base case first if n == 0: # base case: stop here

    countdown(3) prints 3, 2, 1, and when n reaches 0 it prints Done! and returns. It is safe here because the demo passes a non-negative int, but as the problem section showed, do not trust every input.

  2. Combine on the way back return n * factorial(n - 1)

    n * ... can only be computed after factorial(n - 1) returns, so frames wait on the stack and the results climb back as 1, 2, 6, 24, 120.

  3. Two calls per level return fib(n - 1) + fib(n - 2)

    Each call makes two more, so the number of calls grows exponentially: 21,891 for fib(20), and hundreds of millions for fib(40).

  4. Memoization decorator@lru_cache(maxsize=None)

    lru_cache remembers the result for each argument, so fib_memo(20) truly computes only the 21 values from 0 to 20 (21 cache misses). Every other call is answered from the cache.

  5. Recursing into children size += total_size(child)

    A folder's size is the sum of its files plus the size of each subfolder. With no subfolders the for loop does nothing, which is the implicit base case. 2665 KB is the sum of every file in the tree.

  6. Hitting the limit factorial(5000)

    It needs 5000 nested calls but the limit is 1000, so RecursionError is raised and caught, letting the program continue. math.factorial(5000) has no such problem because it does not recurse in Python.

You should see
===== Countdown =====
3
2
1
Done!

===== Factorial =====
5! = 120

===== Fibonacci =====
fib(20) = 6765 using 21891 calls
fib_memo(20) = 6765, cache misses: 21

===== Nested folders =====
Total size: 2665 KB

===== Depth limit =====
Recursion limit: 1000
factorial(5000) -> RecursionError

Turning recursion into a loop with an explicit stack

Recursion quietly uses Python's call stack. Manage that stack yourself with a list and the depth limit disappears. The pattern is short: start with stack = [root], then inside while stack: take node = stack.pop(), process the node and push its children with stack.extend().

Recursive code reads beautifully on tree-shaped data. When you do not control the depth, such as JSON uploaded by users or a long chain, choose the iterative version. If the data is a graph that may contain cycles, remember the nodes you have visited in a set; otherwise both the recursive and the iterative versions loop forever.

Where the standard library hides the recursion

To walk folders use os.walk() or pathlib.Path.rglob("*"); for factorials use math.factorial(); for JSON use json.loads(). Hand-written recursion is for data structures that have no standard tool.

In real projects

In real projects

Recursion appears wherever data is tree-shaped: an e-commerce category tree (Books > Programming > Python), threaded comment replies, an organisation chart, the HTML DOM, nested JSON configuration and the file system. Building a breadcrumb, counting the products in every subcategory, or drawing an indented menu are each a short recursive function.

In production you rarely control how deep the data goes. If an admin accidentally makes a category its own parent, there is a cycle, and code without a visited set never stops. That is why teams test both the recursive and the iterative versions against a normal tree, a very deep chain and data containing a cycle. Many teams also store each category's depth or full path in the database, so common pages never need to recurse at request time.

Common mistakes

Common mistakes

Forgetting to return the recursive result

Writing find(child, target) without return inside def find(node, target) means the match is found but never travels up a frame, and the function returns None. Whenever you need the recursive call's value, return it or store it in a variable.

Using an exact equality as the only stop

if n == 0 only works if n drops by exactly one each time. A function that recurses with n - 2, a float input or a negative input skips past 0. Use a range check such as if n <= 0 and reject invalid input with ValueError at the start.

Using a mutable default as an accumulator

With def collect(node, found=[]) the default list is shared by every call, so a second top-level collect() still contains items from the first. Default to found=None and create the list inside, or return result lists and concatenate them.

Mini challenge

Walk a category tree

For a category tree shaped like {"name": ..., "children": [...]}, write three recursive functions and one iterative one, then compare recursive and iterative on a 5,000-level chain.

  • count_nodes() counts every node, including the root
  • max_depth() treats a node without children as depth 1
  • find_path() returns the list of names from root to target, or None if absent
  • count_nodes_iterative() uses a list as a stack and no recursion at all
category_tree.py
Category = dict  # {"name": str, "children": list[Category]}


def count_nodes(node: Category) -> int:
    # TODO: 1 for this node + the count of every child subtree
    ...


def max_depth(node: Category) -> int:
    # TODO: base case: no children -> 1
    # TODO: otherwise 1 + the deepest child
    ...


def find_path(node: Category, target: str) -> list[str] | None:
    # TODO: found here -> [name]; else try each child and prepend name
    ...


def count_nodes_iterative(root: Category) -> int:
    # TODO: stack = [root]; pop, count, push children until empty
    ...


shop = {
    "name": "Shop",
    "children": [
        {"name": "Books", "children": [{"name": "Python"}, {"name": "Poetry"}]},
        {"name": "Music", "children": [
            {"name": "Jazz", "children": [{"name": "Bebop"}]},
        ]},
    ],
}
# TODO: print node count, depth, the path to "Bebop" and to "Rock"
# TODO: build a 5,000-level chain and compare both counting functions

Expected: Nodes: 7, depth: 4, the path to Bebop is ['Shop', 'Music', 'Jazz', 'Bebop'] and the path to Rock is None. On the deep chain the iterative version counts 5001 nodes and the recursive one hits RecursionError.

Show hint

In find_path(), as soon as a child returns a path that is not None, return [node["name"], *path]. Build the deep chain with a loop, not with recursion.

Show solution
category_tree.py
Category = dict  # {"name": str, "children": list[Category]}


def count_nodes(node: Category) -> int:
    return 1 + sum(count_nodes(child) for child in node.get("children", []))


def max_depth(node: Category) -> int:
    children = node.get("children", [])
    if not children:
        return 1
    return 1 + max(max_depth(child) for child in children)


def find_path(node: Category, target: str) -> list[str] | None:
    if node["name"] == target:
        return [node["name"]]
    for child in node.get("children", []):
        path = find_path(child, target)
        if path is not None:
            return [node["name"], *path]
    return None


def count_nodes_iterative(root: Category) -> int:
    stack = [root]
    count = 0
    while stack:
        node = stack.pop()
        count += 1
        stack.extend(node.get("children", []))
    return count


shop = {
    "name": "Shop",
    "children": [
        {"name": "Books", "children": [{"name": "Python"}, {"name": "Poetry"}]},
        {"name": "Music", "children": [
            {"name": "Jazz", "children": [{"name": "Bebop"}]},
        ]},
    ],
}
print(f"Nodes: {count_nodes(shop)}, depth: {max_depth(shop)}")
print(f"Path to Bebop: {find_path(shop, 'Bebop')}")
print(f"Path to Rock:  {find_path(shop, 'Rock')}")

deep = {"name": "level-0"}
current = deep
for i in range(1, 5001):
    current["children"] = [{"name": f"level-{i}"}]
    current = current["children"][0]
print(f"Deep chain (iterative): {count_nodes_iterative(deep)} nodes")
try:
    count_nodes(deep)
except RecursionError:
    print("Deep chain (recursive): RecursionError")

Quick quiz 1 / 3

Given def f(n): return 0 if n == 0 else n + f(n - 1), what does f(4) return?

Quick quiz 2 / 3

A category tree comes from user-uploaded JSON and may be thousands of levels deep. Which approach fits best?

Quick quiz 3 / 3

What is the bug in: def has(node, t): if node["name"] == t: return True; for c in node.get("children", []): has(c, t); return False

What to remember

  • Recursion needs a base case, a smaller subproblem and guaranteed progress towards the base case
  • Each call gets a new stack frame, and answers flow back up from the base case
  • Cache repeated subproblems with @lru_cache
  • CPython's default limit is 1000 with no tail-call optimisation, so use an explicit stack for deep data
  • Recursion shines on trees and nested data; add a visited set when cycles are possible

Python Documentation — Functional Programming HOWTO — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Recursion | Thuta Learning