Recursion: Russian Dolls, the Base Case and the Call Stack
Recursion means doing the same job on a smaller piece of the problem, and stopping at a base case. Count Emma's Russian dolls with a Python function that calls itself, watch each call wait on the call stack so the answers come back in reverse, then take the base case out and meet RecursionError.
What you will learn
- Explain recursion as the same job on a smaller piece, with a base case that stops it
- Trace a recursive Python function down to the base case and back up the call stack
- Explain why the answers come back in reverse order
- Recognise a missing base case and the RecursionError it causes
Before you start
- Python functions
- Stacks
Recursion is a function that calls itself. The idea is simple: do the same job on a smaller piece of the problem, and stop when the piece can't get any smaller.
Russian dolls
Emma has a Russian doll on her shelf. It looks like one doll, but how many dolls are hidden inside it?
To find out, she does the same job again and again. Open the doll. Is there a smaller doll inside? Then do the same job on that one. The tiny doll doesn't open, so she stops there. Then she closes them back up, counting as she goes: one, two, three, four.
Put names to it. Opening the next doll means the function calls itself. The tiny solid doll is the stop rule, called the base case. And the dolls still waiting open on the table? That's the call stack, a stack of waiting calls, just like the plates.
Inside open_doll
def open_doll(size):
if size == 1: # base case
print("doll 1 is solid: stop")
return 1
print(f"open doll {size}")
count = open_doll(size - 1) + 1 # a smaller doll
print(f"close doll {size}, count {count}")
return count
The first three lines inside are the base case. If size == 1, the tiny doll is solid, so it prints stop and returns 1. Otherwise it prints open doll with its size. Then comes the interesting line: open_doll calls itself with size - 1, a smaller doll, and adds one for this doll to whatever count comes back. Finally it prints close doll and hands the count back.
Every call gets a smaller doll, and that's why you always reach the base case.
Count Emma's dolls
from dolls import open_doll
total = open_doll(4)
print(f"dolls counted: {total}")
open doll 4
open doll 3
open doll 2
doll 1 is solid: stop
close doll 2, count 2
close doll 3, count 3
close doll 4, count 4
dolls counted: 4
Open 4, 3, 2. Doll 1 is solid, stop. Then the closes come in reverse order: 2, 3, 4. Why reverse? Watch the call stack.
Play it step by step
The main script calls open_doll(4), and it goes on the call stack. Size 4 isn't 1, so it prints open doll 4, then calls open_doll(3) and waits. Three isn't 1 either: open doll 3, call open_doll(2), wait. Open doll 2, call open_doll(1).
Size is 1. Base case. It prints stop, returns 1, and makes no more calls. It leaves the stack, and you're back in open_doll(2), where the count is 1 + 1 = 2: close doll 2. That returns 2 to open_doll(3), whose count is 3. Then open_doll(4) gets 4, returns it to the main script, and the stack is empty again.
The call stack remembers every call that's still waiting. That's why the closes come in reverse order.
Two rules every recursive function needs
Rule one: every call must make the problem smaller. Doll 4, then 3, then 2, then 1. Each step gets closer to the tiny doll. If a call handed doll 4 to a new call, which handed doll 4 to another, it would never get closer to the stop and never end.
Rule two: the smallest piece needs a base case. Doll 1 is solid, so it answers right away and starts no more calls.
No base case
Now break it. Take the base case out:
print("opening 4 dolls...")
def open_doll(size):
# no base case: nothing ever says stop
count = open_doll(size - 1) + 1
return count
total = open_doll(4)
print(f"dolls counted: {total}")
opening 4 dolls...
Traceback (most recent call last):
...
count = open_doll(size - 1) + 1
~~~~~~~~~^^^^^^^^^^
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
(The file paths in the traceback are trimmed.) Nothing ever says stop, so it calls with 3, 2, 1, 0, -1, and on. Doll 0 doesn't even exist, and still nobody checks. Every call waits on the call stack, so the stack only grows. The stack has limited room, so Python gives up with a RecursionError, and "dolls counted" is never printed. Other languages call this a stack overflow.
One call per doll
| Cost | For n dolls | Why |
|---|---|---|
| Time | O(n) | one call per doll |
| Memory | O(n) | at the deepest point, all n calls wait on the stack |
| No base case | crash | the stack fills up |
The memory row matters. With a million dolls, a million calls would wait at once, and that wouldn't fit even with a base case. Python's limit is about a thousand calls deep by default, so very deep problems are usually rewritten as a loop.
Where you meet recursion
Folders inside folders: to find a file, open a folder and do the same job on every folder inside it. Sorting: a popular method splits the list in halves and does the same job on each half. Trees, like a family tree: do the same job on each branch, and every branch has smaller branches. Mazes and puzzles: try a move, do the same job on what's left, and step back when you get stuck.
Recap
- Recursion is a function that calls itself on a smaller problem.
- The base case stops it. The call stack remembers every call still waiting, so answers come back in reverse order.
- Without a base case, or if the pieces don't shrink, the stack fills up and you get a
RecursionError.
Try it yourself: in doll_app.py, open a set of six dolls instead of four. Guess the output first, then run it and check.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related courses on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Data Structures and Algorithms Concepts: No Coding Needed
How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)Related posts
Big-O: Reading Cost From Code, With Handshakes and a Guest Book
Big-O asks one question: how do the steps grow when the list grows? Check a school trip sheet for duplicates two ways, handshakes and a guest book, count every step in Python, then grow the list to ten thousand ids and watch 10,000 steps turn into almost 50 million.
Linear vs Binary Search: Page by Page, or Open in the Middle
Is kite a real word? Page by page takes 11 checks; opening in the middle takes 4. Trace binary search step by step, see a million words answered in 20 checks, and watch it give the wrong answer on an unsorted list.
Insertion Sort: Take the Next Card and Slide It Left Until It Fits
Emma's hand 7, 3, 9, 2, 5 sorted one card at a time in 6 shifts. Trace each card, see why a backwards hand costs the most, why 5,000 shuffled cards need over 6 million shifts, and why a sorted hand needs zero.
Merge Sort: Split the Pile, Then Merge Two Sorted Piles
Ms Kate's eight exam papers sorted in 24 steps: split in half until each pile is one paper, then merge sorted piles by taking the lower top. A million papers take about 20 million steps, and the price is extra room.
