Python Recursion: How Recursive Functions Work and How to Trace Them

Recursion is when a function calls itself to solve a problem by breaking it into smaller versions of the same problem. It works only when the function has a base case that stops the repeated calls; without that stop, Python raises RecursionError. This article shows how to trace recursion by hand, how the call stack grows and shrinks, common base case mistakes, and when a loop is the better choice.

Difficulty: Beginner

Helpful to know first: basic Python functions, variables, and how if statements control program flow.

How Recursion Solves a Problem One Smaller Step at a Time

Recursion is a technique, not a special syntax. You write a function that solves part of a problem, then calls itself on a smaller input until it reaches a base case. The base case is the simplest possible input, where the answer is known immediately and no more recursive calls are needed.

Think of it like walking down a staircase one step at a time. Each call solves one step and asks the next call to solve the remaining steps. When the base case is reached, the answers start returning back up the stack in reverse order.

Here is the smallest useful recursive function in Python:

Python
def countdown(n : int) -> None:
    if n == 0:
        print("Done")
        return

    print(n)
    countdown(n - 1)

countdown(3)
# Output:
# 3
# 2
# 1
# Done

This function prints the current number, then calls itself with a smaller number. When n reaches 0, the base case prints "Done" and stops the recursion.

A recursive function must always move toward its base case. If the input does not get smaller or simpler, the function can keep calling itself forever.

Tracing Recursion by Hand with a Call Stack Table

To understand recursion, trace it like a stack of unfinished work. Each function call creates a new stack frame that remembers its local variables and the point where execution should continue after the recursive call returns.

Use this factorial example, which multiplies a number by the factorial of the number one smaller:

Python
def factorial(n : int) -> int:
    if n == 1:
        return 1
    return n * factorial(n - 1)

print(factorial(4))
# Output: 24

Here is the call stack view for factorial(4):

CallCurrent value of nWhat happens next
14Waits for factorial(3)
23Waits for factorial(2)
32Waits for factorial(1)
41Returns 1

Now the returns happen in reverse order:

  • factorial(1) returns 1
  • factorial(2) returns 2 * 1 = 2
  • factorial(3) returns 3 * 2 = 6
  • factorial(4) returns 4 * 6 = 24

That reverse order is the key idea. The first call is not finished until every deeper call has finished.

Worked Examples of Recursion in Python

Summing a list by reducing one item at a time

This version adds the first item to the sum of the rest of the list. The list gets shorter on each call until it becomes empty.

Python
def sum_items(items: list[int]) -> int:
    if not items:
        return 0
    return items[0] + sum_items(items[1:])

print(sum_items([2, 4, 6]))
# Output: 12

The base case is the empty list. Without it, the function would try to access items[0] even when there are no items left.

Searching a nested structure

Recursion is useful when the data is nested, because each level can be processed the same way. This example counts how many times a target value appears in a nested list.

Python
def count_target(data, target):
    if isinstance(data, int):
        return 1 if data == target else 0

    if not data:
        return 0

    return count_target(data[0], target) + count_target(data[1:], target)

print(count_target([1, [2, 1], [1, [1]]], 1))
# Output: 4

This function shows a common recursive pattern: handle one small part now, then call the same function on the remaining parts.

Traversing a folder tree

Recursive functions are often used for tree-shaped data, such as directories inside directories. The same logic applies at every level.

Python
from pathlib import Path

def count_files(path: Path) -> int:
    if path.is_file():
        return 1

    total = 0
    for child in path.iterdir():
        if child.is_dir():
            total += count_files(child)
        else:
            total += 1
    return total

This example is partly recursive and partly iterative. The function uses recursion to move through subdirectories, but a loop to examine each child in the current directory.

Computing a power with repeated multiplication

Recursion can express repeated work in a compact form. This example raises a number to a non-negative integer power.

Python
def power(base: int, exponent: int) -> int:
    if exponent == 0:
        return 1
    return base * power(base, exponent - 1)

print(power(2, 5))
# Output: 32

The recursive version is easy to read, but Python also has the built-in ** operator for this job. That matters when choosing between recursion and a direct language feature.

How Python Actually Runs Recursive Calls

Each recursive call gets its own stack frame. A stack frame stores local variables like n, the line being executed, and information needed to return to the caller. The previous call is paused while the new call runs.

This means recursion uses more memory than a loop, because every call adds another frame. It also means Python limits recursion depth to protect the interpreter from using too much stack space. If you go too deep, Python raises RecursionError: maximum recursion depth exceeded.

Here is a direct example of that error:

Python
def go_forever(n):
    return go_forever(n + 1)

go_forever(0)
# RecursionError: maximum recursion depth exceeded

That error does not mean recursion is broken. It means the function never reaches a base case, so Python keeps creating frames until it hits the safety limit.

Python does not optimize tail recursion. Even if the recursive call is the last thing a function does, Python still creates a new frame for it. That is one reason loops are often a better choice for simple repetition in Python.

Predict the Output

What happens when the base case is missing one step?

Python
def mystery(n):
    if n == 0:
        return
    print(n)
    return mystery(n - 2)

mystery(5)

What does this print?

Show answer

It prints 5, then 3, then 1. After that, the next call is mystery(-1), which does not match the base case n == 0. The function keeps calling itself with smaller negative numbers until Python raises RecursionError.

The mistake is that the base case is too specific. It stops only at exactly zero, but the recursive step skips past zero.

Why does this factorial example fail?

Python
def factorial(n):
    if n == 0:
        return 0
    return n * factorial(n - 1)

print(factorial(3))

What happens?

Show answer

This prints 0. The recursive calls are made, but every return gets multiplied by 0 at the base case, so all results become zero. The correct base case for factorial is return 1 when n == 0.

Common Mistakes with Recursion

Using the wrong base case value

Many recursive functions stop at the right input but return the wrong answer for that input. That often makes every result wrong.

Problem: The base case returns the wrong value, so the recursion reaches the stop point but still produces the wrong final result.

Python
def factorial(n):
    if n == 0:
        return 0
    return n * factorial(n - 1)

print(factorial(4))
# Output: 0

Fix: Return the mathematically correct value for the base case.

Python
def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

print(factorial(4))
# Output: 24

The corrected version works because the recursion multiplies by 1 at the stop point, which leaves the result unchanged.

Moving away from the base case instead of toward it

If the recursive step makes the problem larger, the function never finishes.

Problem: This function adds 1 instead of subtracting it, so it moves farther from the stopping point on every call.

Python
def countdown(n):
    if n == 0:
        return
    print(n)
    return countdown(n + 1)

countdown(3)

Fix: Make the recursive step simpler or smaller so it eventually reaches the base case.

Python
def countdown(n):
    if n == 0:
        return
    print(n)
    return countdown(n - 1)

countdown(3)
# Output:
# 3
# 2
# 1

The fixed version works because each call gets closer to the stop condition.

Forgetting that the empty case also needs a stop

When recursion works on lists or strings, the empty value is often the base case. If you skip it, indexing or slicing can fail.

Problem: This function tries to read items[0] even when the list is empty, which causes an IndexError.

Python
def first_item(items):
    return items[0] + first_item(items[1:])

print(first_item([]))
# IndexError: list index out of range

Fix: Stop when the sequence is empty before reading the first element.

Python
def first_item(items):
    if not items:
        return 0
    return items[0] + first_item(items[1:])

print(first_item([4, 5]))
# Output: 9

The empty-sequence check prevents the function from reading past the end of the list.

Assuming recursion is always the best choice

Recursion can be elegant, but it is not always practical. A simple loop is often easier to read and avoids deep call stacks.

Problem: This recursive version works, but it is harder to follow than a loop for a simple count, and a large input can hit recursion depth limits.

Python
def count_to_n(n):
    if n == 0:
        return
    count_to_n(n - 1)
    print(n)

count_to_n(3)

Fix: Use a loop when the task is straight-line repetition and does not naturally break into smaller self-similar problems.

Python
for n in range(1, 4):
    print(n)
# Output:
# 1
# 2
# 3

The loop is clearer here because it does not need an extra stack frame for every number.

Find the Bug

This function is meant to sum all numbers in a nested list structure, but it has one subtle recursion bug. Find the mistake before looking at the answer.

Python
def nested_sum(data):
    if isinstance(data, int):
        return data

    if not data:
        return 0

    return nested_sum(data[0]) + nested_sum(data[0:])

print(nested_sum([1, [2, 3], 4]))
Show answer

The bug is in the second recursive call. It uses data[0:], which returns the entire list again, so the function never makes progress toward the base case for lists. That causes repeated work and eventually RecursionError.

Fixed code:

Python
def nested_sum(data):
    if isinstance(data, int):
        return data

    if not data:
        return 0

    return nested_sum(data[0]) + nested_sum(data[1:])

print(nested_sum([1, [2, 3], 4]))
# Output: 10

The fixed version works because each call reduces the list by one element.

When Recursion Is Better and When a Loop Is Better

Recursion is best when the problem naturally breaks into smaller versions of itself, especially for trees, nested structures, and divide-and-conquer algorithms. A loop is better for simple repetition, counting, and tasks that do not benefit from keeping suspended function calls on the stack.

Use recursion when...Use a loop when...
The problem is naturally tree-shaped or nested.The work is linear and repetitive.
You need a clear base case and smaller subproblems.You want the simplest and most memory-efficient solution.
The recursive version is easier to reason about.The same logic can be written with for or while clearly.
You are implementing algorithms like traversal, parsing, or divide and conquer.You are just counting, accumulating, or iterating through items.

For example, traversing a folder tree is a natural recursive task. Printing numbers from 1 to 100 is usually better done with a loop.

One more point matters in Python: recursion depth. Even correct recursive code can fail on very deep input if the depth gets too large. A loop does not have that limit in the same way.

Interview Questions About Recursion

What is the base case in recursion?

The base case is the condition that stops the function from calling itself. It is the simplest input where the answer can be returned directly without more recursion.

Why can recursion be slower than a loop in Python?

Each recursive call creates a new stack frame, which adds overhead. A loop usually uses less memory and avoids the cost of many function calls.

What does a recursive function need to be correct?

It needs a base case and a recursive step that moves toward that base case. Without both, the function may loop forever or return the wrong result.

When should you avoid recursion?

Avoid recursion when the task is simple iteration, when deep input may exceed Python's recursion limit, or when a loop is easier to understand and maintain.

Try It Yourself

Write a recursive function that counts how many odd numbers are in a list of integers.

  • If the list is empty, the answer should be 0.
  • For a non-empty list, look at the first item, then recurse on the rest of the list.
  • Print the result for [3, 8, 5, 10, 7].

Expected output:

Python
3

Hint: Use items[0] for the first item and items[1:] for the rest. Count 1 when the first item is odd and 0 otherwise.

Show solution
Python
def count_odds(items):
    if not items:
        return 0

    first = items[0]
    rest = items[1:]

    if first % 2 != 0:
        return 1 + count_odds(rest)
    return count_odds(rest)

print(count_odds([3, 8, 5, 10, 7]))
# Output: 3

Summary

  • Recursion means a function calls itself to solve a smaller version of the same problem.
  • Every recursive function needs a base case that stops the calls.
  • Each call uses its own stack frame, so deep recursion can raise RecursionError.
  • Tracing recursion by hand is easier if you write down the call stack and follow the returns in reverse order.
  • Base case mistakes are common: the stop condition may be wrong, skipped, or return the wrong value.
  • Use recursion for nested or tree-shaped problems; use a loop for simple repetition.

Next, study Python call stacks and stack frames in more detail so recursive code becomes easier to debug and trace.