Unays Learn · Computer science

Recursion explained: functions that call themselves

A recursive function solves a problem by calling itself on a smaller version of the same problem. It is a powerful idea that appears everywhere from file systems to sorting algorithms.

The idea

Every recursive function needs two parts:

  • A base case: a version of the problem so small you can answer it directly.
  • A recursive case: a step that makes the problem smaller and calls the function again.
def countdown(n):
    if n == 0:           # base case
        print("Lift off!")
        return
    print(n)
    countdown(n - 1)     # smaller problem

countdown(3)  # 3 2 1 Lift off!

Factorial

The factorial of 5 is 5 × 4 × 3 × 2 × 1 = 120. Notice that 5! = 5 × 4!, which is a smaller version of the same problem:

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

print(factorial(5))  # 120

The calls pile up as factorial(5) → factorial(4) → … → factorial(1), which returns 1. Then each waiting call multiplies and returns, unwinding back to the top. The computer keeps track of the waiting calls on the call stack.

Recursion on lists

def total(numbers):
    if not numbers:          # an empty list sums to 0
        return 0
    return numbers[0] + total(numbers[1:])

print(total([4, 8, 15, 16]))  # 43

The sum of a list is its first item plus the sum of the rest.

Where recursion shines: trees

Recursion is most natural for data that contains smaller versions of itself, like folders inside folders:

folder = {
    "name": "school",
    "files": ["timetable.pdf"],
    "folders": [
        {"name": "math", "files": ["algebra.txt", "geometry.txt"], "folders": []},
        {"name": "art", "files": [], "folders": [
            {"name": "photos", "files": ["sketch.png"], "folders": []}
        ]},
    ],
}

def count_files(f):
    return len(f["files"]) + sum(count_files(sub) for sub in f["folders"])

print(count_files(folder))  # 4

Writing this with loops is possible but much more awkward, because you do not know in advance how deep the folders go.

Common mistakes

  • No base case, or one that is never reached, makes the function call itself forever. Python stops it with RecursionError: maximum recursion depth exceeded (the default limit is about 1000 calls).
  • Not making the problem smaller: every call must move towards the base case.
  • Using recursion for simple repetition: for counting or walking a long list, an ordinary loop is clearer and does not hit the depth limit.

Try it yourself

In Unays Code, write recursive functions to reverse a string, to compute the n-th Fibonacci number, and to find the largest number in a list. Then rewrite the Fibonacci one with a loop and compare how fast each is for n = 30.

This tutorial was written with AI assistance and reviewed by Unays. The runnable code examples were tested before publishing. Spotted a mistake? Tell us at [email protected].