Skip to the workspace
Pebellslearn by building
Data Structures in Practice  ›  Lesson

Recursion

Recursion 16 minA recursive function solves a problem by calling itself on related subproblems and combining the returned results.

A recursive function solves a problem by calling itself on related subproblems and combining the returned results.

Inspect separate call frames, explain a base case and prove that recursive calls move toward completion.

A recursive call leaves work waiting until a smaller call returns. Follow those waiting frames, then prove that each call moves toward a base case. The same reasoning applies to digits, nested lists, and the subtree functions from the previous lesson. Input domains and cycles matter as much as writing the recursive call itself.

A staircase of five boxes labelled factorial(5), factorial(4), factorial(3), factorial(2), factorial(1) stacking upward, factorial(1) marked "base case — returns 1, no further call"; then the same five boxes collapsing back down the other side, each one multiplying in its own number as it returns: 1, then 2, then 6, then 24, then 120

Follow the multiplication waiting in each frame

For a non-negative integer, factorial multiplies the positive integers up to that value. The recursive version keeps one multiplication waiting in each call while the smaller call computes its answer:

python

Step through it and watch the calls pile up before any of them return:

step through it
1def factorial(n):
2 if n <= 1:
3 return 1
4 result = n * factorial(n - 1)
5 return result
6 
7print(factorial(4))

factorial(4) can't finish its multiplication until factorial(3) returns a value — which can't finish until factorial(2) returns — all the way down to factorial(1), the base case, which returns 1 with no further call. Then every waiting multiplication resolves, one level at a time, on the way back up: 1, then 2, then 6, then 24. The mistake people make reading this code for the first time is assuming the multiplications happen on the way down — they don't. Nothing multiplies until the base case is hit and the unwinding starts.

Preparing this topic’s interactive investigation…

Keep each call's local value separate

A countdown makes the same waiting-call structure visible as a returned list. Each frame contributes its own number before the smaller call's result:

What does this print?
def countdown(n):
    if n == 0:
        return ["liftoff"]
    return [n] + countdown(n - 1)

print(countdown(3))

Two different calls to countdown never share one n — countdown(3)'s local n is 3 for its entire lifetime, even though it's sitting on the stack waiting on countdown(2), whose own n is 2 in a completely separate frame. That independence is what makes recursion safe at all: if every call shared the same variables, this would break the moment two calls were alive at once.

Diagnose a call that cannot stop

The next function keeps creating a larger problem instead of reaching a base case. Before changing it, identify the intended final value and the condition that must be checked before printing or making another call:

broken — fix itRecursionError

Run it and watch it crash. Then make it print 1 through 5 and stop.

Every working recursive function needs two things: at least one case that returns without recursing (the base case), and a guarantee that every recursive call moves strictly closer to it. count_up has neither — n only ever grows, so no condition ever stops it, and Python eventually refuses to add one more frame.

Prove that every call moves toward an answer

Before writing a recursive step, state its input domain and a measure that strictly decreases. For sum_digits, the domain is non-negative integers. When n >= 10, n // 10 is smaller and still in the domain; eventually one digit remains. Negative integers would need a different rule, because -1 // 10 stays -1 and never reaches a non-negative base case.

Waiting frame Smaller call Work after that call returns
sum_digits(407) sum_digits(40) Add 7
sum_digits(40) sum_digits(4) Add 0
sum_digits(4) None: base case Return 4

Unwinding returns 4, then 4, then 11. The zero in the middle is a real digit; it does not terminate the calculation. Each frame keeps its own n, although mutable objects passed between frames can still be shared.

Recursive shape is especially useful for nested lists and trees. For a flat million-item sequence, a loop avoids a frame per item. Python does not promise tail-call elimination; increasing the recursion limit is not a substitute for choosing an appropriate algorithm. Read the configured limit with sys.getrecursionlimit() rather than assuming an exact safe input depth.

Transfer the proof to flatten: each recursive call handles a child list, and an ordinary value contributes one output. This assumes finite, acyclic nesting. A list containing itself needs cycle detection using the identity tools from the data-model section, not just another base case for an empty list.

Quick practice

What does this print?
def mystery(n):
    if n == 0:
        return 0
    return n + mystery(n - 1)

print(mystery(4))
What does this print?
def countdown(n):
    if n == 0:
        return ["liftoff"]
    return [n] + countdown(n - 1)

print(countdown(0))

🎯 Your turn

Write sum_digits(n) recursively. Add up the digits of a non-negative integer n:

  • sum_digits(1234) → 10 (1+2+3+4)
  • sum_digits(5) → 5

Hint — the base case is a single digit: if n < 10: return n. Otherwise, n % 10 peels off the last digit and n // 10 is everything else — return n % 10 + sum_digits(n // 10).

Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below counts down, raises to a power, and flattens a nested list — recursion's natural shape.

Your task
Write sum_digits(n) recursively. Add up the digits of a non-negative integer n. Base case: a single digit returns itself. Otherwise, n % 10 peels off the last digit and n // 10 is everything else. Example: sum_digits(1234) -> 10.

Practice — level up

0/5 solved

Solve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.

Warm-upCount down to zero

Write count_down(n) returning the list [n, n-1, ..., 0], built recursively (no loop).

recursionbase-case
DrillExponentiation, recursively

Write power(base, exp) computing base ** exp recursively (no **, no loop), for a non-negative exp.

recursionbase-case
BuildHow many digits?

Write digit_count(n) returning how many digits a non-negative integer n has, recursively.

recursionbase-case
BossA palindrome, checked from the outside in

Write is_palindrome(s) checking whether s reads the same forwards and backwards, recursively: compare the first and last characters, then recurse on what's left between them.

recursionbase-case
CapstoneFlatten a nested list

Write flatten(nested), returning a flat list containing every non-list value in nested, however deeply the lists are nested inside each other.

recursion
Project context and further resources
sum_digits.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
sum_digits(n) → intAdd up every digit of n, recursively.
try:
returned
No app map for this section yet.
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.