You're in a long queue at a railway ticket counter and want to know your position. You can't see the front. So you ask the person ahead, "What's your position?" They ask the person ahead of them, and so on, until the person at the front says "1". Then each answer comes back down the line, one more each time, until it reaches you. That's recursion: solving a problem by handing a smaller version of the same problem to someone else, until it's small enough to answer directly.
In Python, recursion means a function that calls itself. It's the natural way to handle things that contain smaller copies of themselves, such as folders inside folders, nested comments or family trees. It's also a favourite topic in interviews. This lesson explains how recursion in Python works, what happens in memory, and when a loop is the better choice.
What you need first: Python functions and variable scope and the LEGB rule.
Key terms
- Recursion: a function calling itself to solve a smaller piece of the same problem.
- Base case: the simplest input, which the function answers directly without calling itself. It stops the recursion.
- Recursive case: the part where the function calls itself with a smaller input.
- Call stack: Python's list of functions that have been called but haven't finished yet. Each call gets its own frame with its own local variables.
- Memoisation: saving the results of function calls so the same input is never worked out twice.
Your first recursive function
A countdown, written with recursion instead of a loop:
def countdown(n):
if n == 0: # base case
print("Lift off")
return
print(n)
countdown(n - 1) # recursive case: a smaller problem
countdown(3)
3
2
1
Lift off
Every recursive function needs both parts:
- A base case that returns without calling itself. Here,
n == 0. - A recursive case that calls the function on a smaller input, so it gets closer to the base case each time. Here,
n - 1.
Miss either one and the function never stops.
Recursion in Python: factorial
The factorial of n, written n! and read "n factorial", is n × (n − 1) × ... × 1. So 5! = 5 × 4 × 3 × 2 × 1 = 120.
Notice that 5! = 5 × 4!. And 4! = 4 × 3!. Each factorial is defined using a smaller one, which makes it perfect for recursion:
| In words | In maths |
|---|---|
| The factorial of 1 is 1 (base case) | 1! = 1 |
| The factorial of n is n times the factorial of n − 1 | n! = n × (n − 1)! |
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
print(factorial(10))
120
3628800
What happens at each call
Each call waits for the one it made to finish. Calls go down until the base case, then the answers come back up:
factorial(5) = 5 * factorial(4)
factorial(4) = 4 * factorial(3)
factorial(3) = 3 * factorial(2)
factorial(2) = 2 * factorial(1)
factorial(1) = 1
factorial(2) = 2 * 1 = 2
factorial(3) = 3 * 2 = 6
factorial(4) = 4 * 6 = 24
factorial(5) = 5 * 24 = 120
You can watch it happen by printing on the way down and on the way up:
def factorial(n, depth=0):
indent = " " * depth
print(f"{indent}factorial({n}) called")
if n <= 1:
result = 1
else:
result = n * factorial(n - 1, depth + 1)
print(f"{indent}factorial({n}) returns {result}")
return result
factorial(3)
factorial(3) called
factorial(2) called
factorial(1) called
factorial(1) returns 1
factorial(2) returns 2
factorial(3) returns 6
The call stack
Every time a function is called, Python puts a frame on the call stack, holding that call's local variables. That's why each call to factorial has its own n: they don't overwrite each other. When a call returns, its frame is removed.
Picture a stack of plates: you can only add or remove from the top. factorial(5) sits at the bottom, and factorial(1) goes on top. factorial(1) finishes first, then factorial(2), and so on down.
The stack has a size limit. Python stops at about 1,000 calls deep by default and raises a RecursionError, rather than crashing your computer:
def no_base_case(n):
return no_base_case(n - 1)
no_base_case(5)
RecursionError: maximum recursion depth exceeded
You'll see this error if you forget the base case, or if the input doesn't get smaller each time. Read the traceback: the same line repeated hundreds of times is the giveaway.
You can check the limit with sys.getrecursionlimit():
import sys
print(sys.getrecursionlimit())
1000
sys.setrecursionlimit() can raise it, but if you need to, a loop is usually the better design.
More examples
Sum of a list
The sum of a list is its first item plus the sum of the rest. The sum of an empty list is 0:
def total(numbers):
if not numbers:
return 0
return numbers[0] + total(numbers[1:])
print(total([72, 88, 95, 64]))
319
Reversing a string
The reverse of a string is the reverse of everything after the first character, followed by the first character:
def reverse(text):
if len(text) <= 1:
return text
return reverse(text[1:]) + text[0]
print(reverse("Python"))
nohtyP
Power
xⁿ ("x to the power n") is x × xⁿ⁻¹, and x⁰ is 1:
def power(x, n):
if n == 0:
return 1
return x * power(x, n - 1)
print(power(2, 10))
1024
Where recursion really helps: nested data
The examples above are easy to write with a loop too. Recursion becomes truly useful when data is nested to an unknown depth, like folders inside folders or replies to replies. Here's a list that can contain lists, which can contain more lists:
def flatten(items):
result = []
for item in items:
if isinstance(item, list):
result.extend(flatten(item)) # a smaller problem of the same kind
else:
result.append(item)
return result
print(flatten([1, [2, 3], [4, [5, [6]]], 7]))
[1, 2, 3, 4, 5, 6, 7]
With loops alone, you'd need to know in advance how deep the nesting goes. Recursion doesn't care. The same idea is used to walk through folders, parse JSON and explore trees and graphs in data structures and algorithms.
Fibonacci and why recursion can be slow
Fibonacci numbers start 0, 1, and each next number is the sum of the two before: 0, 1, 1, 2, 3, 5, 8, 13... The direct recursive version is short:
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print([fib(i) for i in range(10)])
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
But it repeats huge amounts of work. fib(5) calls fib(3) twice and fib(2) three times, and the waste grows fast at every level. Counting the calls shows how bad it gets:
calls = 0
def fib(n):
global calls
calls += 1
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
fib(25)
print(calls)
242785
Nearly 2.5 lakh calls to get the 25th number. fib(40) would take hundreds of millions.
Memoisation with lru_cache
The fix is to remember answers you've already worked out. Python's functools.lru_cache does it with one line, called a decorator, placed above the function:
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(100))
354224848179261915075
Now each fib(n) is worked out once, so fib(100) takes 101 calculations. Without the cache it would need about 10²¹ calls (a 1 followed by 21 zeros), which would take a laptop hundreds of thousands of years. This idea, solving each smaller problem once and reusing the answer, is called dynamic programming, an important interview topic.
Recursion vs loops
Anything you can do with recursion, you can do with a loop, and the other way round. Here's factorial as a loop:
def factorial_loop(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
print(factorial_loop(5))
120
| Recursion | Loop | |
|---|---|---|
| Best for | Nested or tree-shaped data, divide-and-conquer | Going through a sequence, counting |
| Memory | One stack frame per call | Constant |
| Depth limit | About 1,000 calls by default | None |
| Speed in Python | Slower, because each call has a cost | Faster |
Our advice for Python: use loops for simple repetition, and recursion for nested structures where a loop would need you to manage your own stack. Unlike some languages, Python doesn't optimise "tail calls", so even neat recursive code still uses one frame per call.
Common mistakes
- No base case, or a base case that's never reached (
n == 0whenngoes 5, 3, 1, −1...). Usen <= 0orn <= 1to be safe. - Not making the input smaller.
factorial(n)callingfactorial(n)loops for ever. - Forgetting
returnon the recursive call.n * factorial(n - 1)withoutreturngivesNone, and the next multiplication fails withTypeError: unsupported operand type(s) for *: 'int' and 'NoneType'. - Using plain recursion for Fibonacci-style problems with overlapping work. Add
lru_cache.
Practice
- Write a recursive function
sum_to(n)that returns 1 + 2 + ... + n.
Show the answer
The base case is 0 (sum is 0); otherwise n plus the sum up to n − 1:
def sum_to(n):
if n <= 0:
return 0
return n + sum_to(n - 1)
print(sum_to(100))
5050
- Write a recursive function that counts the digits of a positive whole number.
Show the answer
A single-digit number has 1 digit. Otherwise it's 1 plus the digits of the number without its last digit:
def count_digits(n):
if n < 10:
return 1
return 1 + count_digits(n // 10)
print(count_digits(4821), count_digits(7))
4 1
- Write a recursive
is_palindrome(text).
Show the answer
A string of length 0 or 1 is a palindrome. Otherwise the first and last characters must match, and the middle must be a palindrome:
def is_palindrome(text):
if len(text) <= 1:
return True
if text[0] != text[-1]:
return False
return is_palindrome(text[1:-1])
print(is_palindrome("malayalam"), is_palindrome("python"))
True False
- Find the GCD of two numbers recursively using Euclid's rule: gcd(a, b) = gcd(b, a % b), and gcd(a, 0) = a.
Show the answer
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
print(gcd(48, 18), gcd(17, 5))
6 1
- A dictionary of folders holds file sizes in MB, with subfolders as nested dictionaries. Write a function that returns the total size.
drive = {"notes.pdf": 2, "photos": {"goa.jpg": 4, "trip": {"beach.jpg": 5}}, "cv.docx": 1}
Show the answer
For each entry, add the number directly, or recurse into a dictionary:
def total_size(folder):
size = 0
for value in folder.values():
if isinstance(value, dict):
size += total_size(value)
else:
size += value
return size
drive = {"notes.pdf": 2, "photos": {"goa.jpg": 4, "trip": {"beach.jpg": 5}}, "cv.docx": 1}
print(total_size(drive))
12
2 + 4 + 5 + 1 = 12. The base case is hidden: a folder with no subfolders makes no recursive calls.
Interview questions
What are the two parts every recursive function needs?
A base case that returns an answer directly, and a recursive case that calls the function on a smaller input that moves towards the base case. Without a reachable base case the function recurses until Python raises RecursionError.
What is the time complexity of naive recursive Fibonacci, and how do you improve it?
About O(2ⁿ), because each call makes two more and the same values are recomputed many times. Memoisation (for example functools.lru_cache) or a bottom-up loop brings it down to O(n).
Does Python support tail call optimisation?
No. Every call adds a frame to the stack, even when the recursive call is the last thing the function does. That's why deep recursion hits the recursion limit in Python, and why loops are preferred for long, simple repetition.
Key takeaways
- A recursive function calls itself on a smaller input until it reaches a base case.
- Each call gets its own stack frame with its own variables; answers come back in reverse order.
- Python stops at about 1,000 nested calls with
RecursionError. - Recursion suits nested data such as folders, trees and JSON; loops suit simple repetition.
- Overlapping recursive calls are slow;
functools.lru_cacheremembers answers and fixes that.
Frequently asked questions
Is recursion faster than a loop in Python?
No. Function calls have overhead, so a loop is usually faster and uses less memory. Choose recursion when it makes the code much clearer, as with nested data.
How do I fix RecursionError: maximum recursion depth exceeded?
First check that your base case exists and is always reached. If the logic is right but the input is genuinely deep, rewrite the function as a loop, or raise the limit carefully with sys.setrecursionlimit().
Where is recursion used in real projects?
Walking folder trees, parsing nested JSON or HTML, sorting algorithms like merge sort and quicksort, searching trees and graphs, and solving puzzles by trying options (backtracking).
What to learn next
- Pass functions around as values in lambda, map, filter and sorted.
- Measure how fast recursive solutions are with Big-O notation.
- Revisit closures and scope in variable scope and the LEGB rule.