Recursion is a technique where a function calls itself to solve a problem. Instead of solving a big problem in one go, a recursive function breaks it into a smaller version of the same problem, solves that, and repeats until the problem becomes so small that the answer is obvious.
Recursion is used everywhere in programming: calculating factorials, walking through folders on a disk, searching sorted data, processing nested lists and JSON, and working with trees and graphs. Once you understand it, many problems that look hard with loops become short and elegant.
In this tutorial, you will learn how recursion works in Python, how Python tracks recursive calls with the call stack, the different types of recursion, the recursion limit, how to speed up recursive functions with memoization, and when you should use a loop instead.
Table of contents
- What is Recursion in Python?
- A Simple Recursion Example
- How Recursion Works: The Call Stack
- Recursion Examples in Python
- 1. Sum of Natural Numbers
- 2. Sum of a List
- 3. Power of a Number
- 4. Reverse a String
- 5. Check if a String is a Palindrome
- 6. Sum of Digits of a Number
- 7. Fibonacci Series
- 8. Greatest Common Divisor (GCD)
- 9. Binary Search
- 10. Flatten a Nested List
- 11. Tower of Hanoi
- 12. Generate All Permutations
- 13. Walk Through Nested Folders
- Types of Recursion
- Python Recursion Limit
- Memoization: Speed Up Recursion
- Recursion vs Iteration
- When to Use Recursion
- Advantages and Disadvantages of Recursion
- Common Mistakes in Recursion
- Summary
What is Recursion in Python?
A recursive function is a function that calls itself during its execution. Each call works on a smaller or simpler input than the previous one, and the calls stop when the input reaches a simple case that can be answered directly.
A real-life analogy: imagine you are standing in a long queue and want to know your position. You ask the person in front of you, “What is your position?” They ask the person in front of them, and so on. The person at the very front knows they are number 1 (this is the base case). That answer travels back down the line, and each person adds 1 to it until the answer reaches you.
Every recursive function has two essential parts:
- Base case: The condition under which the function stops calling itself and returns a value directly. Without a base case, the function would call itself forever.
- Recursive case: The part where the function calls itself with a smaller or simpler input, moving step by step toward the base case.
Syntax:
def recursive_function(parameters):
if base_condition: # Base case: stop here
return base_value
else: # Recursive case: call itself with a smaller input
return recursive_function(smaller_parameters)Code language: Python (python)
A Simple Recursion Example
Letโs start with a function that counts down from a given number to 1.
Output:
5
4
3
2
1
Done!Code language: Python (python)
Here is what happens:
countdown(5)prints 5 and callscountdown(4).countdown(4)prints 4 and callscountdown(3), and so on.- When
nbecomes 0, the base case runs, printsDone!, and the function stops calling itself.
Notice that each call passes n - 1. This guarantees that n eventually reaches 0. A recursive function must always make progress toward its base case.
How Recursion Works: The Call Stack
To really understand recursion, you need to know what Python does behind the scenes when a function calls itself.
Each time a function is called, Python creates a stack frame. A frame stores that callโs local variables and the point where execution should continue when it returns. Frames are placed on the call stack, which works like a stack of plates: the most recent call sits on top, and it must finish before the calls below it can continue.
Letโs trace the classic factorial function. The factorial of n (written n!) is the product of all positive integers up to n: 5! = 5 ร 4 ร 3 ร 2 ร 1 = 120. It can be defined recursively as n! = n ร (n - 1)!, with 0! = 1 and 1! = 1.
Output:
120Code language: Python (python)
Recursion happens in two phases:
- Winding phase (going down): The function keeps calling itself and frames pile up on the stack until the base case is reached. No multiplication has happened yet; each frame is waiting for the result of the call below it.
- Unwinding phase (coming back up): The base case returns 1. Each waiting frame then receives the result, finishes its multiplication, returns, and is removed from the stack.
factorial(5)
= 5 * factorial(4)
= 5 * (4 * factorial(3))
= 5 * (4 * (3 * factorial(2)))
= 5 * (4 * (3 * (2 * factorial(1))))
= 5 * (4 * (3 * (2 * 1))) <- base case reached, start unwinding
= 5 * (4 * (3 * 2))
= 5 * (4 * 6)
= 5 * 24
= 120Code language: Python (python)
You can watch both phases by adding print statements and an indentation level that shows how deep each call is:
Output:
factorial(4) called
factorial(3) called
factorial(2) called
factorial(1) called
base case reached, returning 1
factorial(2) returns 2
factorial(3) returns 6
factorial(4) returns 24Code language: Python (python)
The calls go deeper (winding) until factorial(1), and then the results come back in reverse order (unwinding). This “last in, first out” behavior is exactly how a stack works.
Recursion Examples in Python
The best way to get comfortable with recursion is to practice on small problems. For each example, look for the base case and ask how the input gets smaller on every call.
1. Sum of Natural Numbers
The sum of the first n natural numbers is n plus the sum of the first n - 1 numbers.
Output:
55Code language: Python (python)
2. Sum of a List
The sum of a list is the first element plus the sum of the rest of the list. An empty list has a sum of 0.
Output:
108Code language: Python (python)
Note: numbers[1:] creates a new list on every call, which costs extra time and memory. For large lists, pass an index instead of slicing:
Output:
108Code language: Python (python)
3. Power of a Number
baseexp equals base ร baseexp - 1, and any number raised to the power 0 is 1.
Output:
1024
125Code language: Python (python)
This makes exp recursive calls. A smarter version, called fast exponentiation, halves the exponent on each call, so it needs only about log2(exp) calls:
Output:
1024
1594323Code language: Python (python)
4. Reverse a String
Take the last character and attach it to the front of the reversed remaining string.
Output:
evitanYPCode language: Python (python)
5. Check if a String is a Palindrome
A palindrome reads the same forwards and backwards. Compare the first and last characters, then check the inner part of the string.
Output:
True
True
FalseCode language: Python (python)
This function has two base cases. A recursive function can have as many base cases as the problem needs.
6. Sum of Digits of a Number
n % 10 gives the last digit, and n // 10 removes it.
Output:
35Code language: Python (python)
7. Fibonacci Series
In the Fibonacci series, each number is the sum of the two numbers before it: 0, 1, 1, 2, 3, 5, 8, 13, and so on.
Output:
0 1 1 2 3 5 8 13 21 34 Code language: Python (python)
This version is easy to read but very slow for large n, because it calculates the same values again and again. You will learn how to fix this in the memoization section.
8. Greatest Common Divisor (GCD)
Euclidโs algorithm is naturally recursive: the GCD of a and b is the same as the GCD of b and a % b. When b becomes 0, the answer is a.
Output:
6
6Code language: Python (python)
9. Binary Search
Binary search finds an item in a sorted list by checking the middle element and then searching only the left or right half. Each call cuts the search range in half.
Output:
5
-1Code language: Python (python)
10. Flatten a Nested List
Recursion is ideal for data whose depth is unknown in advance. A nested list can contain lists inside lists to any level, so a loop alone cannot handle it easily.
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]Code language: Python (python)
11. Tower of Hanoi
In the Tower of Hanoi puzzle, you move a stack of disks from one rod to another, using a third rod as a helper. You can move only one disk at a time, and a larger disk can never be placed on a smaller one.
The recursive solution is surprisingly short: move the top n - 1 disks out of the way, move the largest disk, then move the n - 1 disks on top of it.
Output:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to CCode language: Python (python)
Solving n disks always takes 2n - 1 moves, so 3 disks take 7 moves.
12. Generate All Permutations
To list every arrangement of a string, fix each character in the first position and recursively arrange the remaining characters.
Output:
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']Code language: Python (python)
In real projects, use itertools.permutations(), but writing it yourself is a great recursion exercise.
13. Walk Through Nested Folders
File systems are trees: a folder can contain files and other folders. The function below prints a folder tree by calling itself for every subfolder it finds.
There is no explicit if base case here. The recursion stops naturally when a folder has no subfolders, because the loop simply ends without making another call.
Types of Recursion
Recursive functions are commonly grouped by how and where they call themselves.
1. Direct Recursion
A function calls itself directly. All the examples above, such as factorial() and countdown(), use direct recursion.
2. Indirect Recursion
Function A calls function B, and function B calls function A. This is also called mutual recursion.
Output:
True
True
FalseCode language: Python (python)
3. Tail Recursion
In tail recursion, the recursive call is the very last operation in the function; nothing is left to do after it returns. The running result is usually passed along in an extra parameter called an accumulator.
Output:
120Code language: Python (python)
Compare it with the regular factorial(), where n * factorial(n - 1) still has to multiply after the call returns, so that version is not tail recursive.
Important: Some languages optimize tail calls so they donโt grow the stack. Python does not perform tail call optimization. A tail-recursive Python function still uses one stack frame per call and is still limited by the recursion limit. The benefit of writing it this way is that it is very easy to convert into a loop.
4. Head Recursion
In head recursion, the recursive call happens first, and the function does its own work after the call returns. Compare these two functions:
Output:
1 2 3 4 5
5 4 3 2 1 Code language: Python (python)
Both functions have the same structure, but moving the print() before or after the recursive call reverses the order of the output.
5. Tree Recursion
A function makes more than one recursive call each time it runs. The calls branch out like a tree. The fibonacci() function and the Tower of Hanoi are examples of tree recursion.
fib(5)
/ \
fib(4) fib(3)
/ \ / \
fib(3) fib(2) fib(2) fib(1)
/ \ / \ / \
fib(2) fib(1) ... ... ...Code language: Python (python)
Notice that fib(3) and fib(2) are calculated several times. The number of calls grows exponentially, roughly O(2n). Memoization solves this problem.
Python Recursion Limit
Because every call adds a frame to the call stack, a function that recurses too deeply could use up all the memory reserved for the stack and crash the program. To prevent this, Python sets a maximum recursion depth. By default, it is 1000.
You can check it with sys.getrecursionlimit():
Output:
1000Code language: Python (python)
If a function goes deeper than this limit, Python raises a RecursionError:
Output:
RecursionError: maximum recursion depth exceededCode language: Python (python)
The same error appears if you forget the base case, because the function never stops calling itself:
Output:
Traceback (most recent call last):
...
File "main.py", line 2, in no_base_case
return no_base_case(n - 1) # No base case: infinite recursion
~~~~~~~~~~~~^^^^^^^
RecursionError: maximum recursion depth exceededCode language: Python (python)
Changing the Recursion Limit
You can raise the limit with sys.setrecursionlimit():
Output:
factorial(3000) computed successfully
It has 30332 bitsCode language: Python (python)
Use this carefully. The recursion limit is a safety net. Setting it too high can make Python crash with a segmentation fault instead of a clean RecursionError, because the real operating system stack runs out. If you need very deep recursion, it is usually better to rewrite the function with a loop.
Memoization: Speed Up Recursion
Memoization means storing the result of a function call and reusing it the next time the same input appears, instead of calculating it again. It is the standard fix for slow tree-recursive functions such as Fibonacci.
First, letโs count how many calls the plain Fibonacci function makes:
Output:
75025
Function calls: 242785Code language: Python (python)
Nearly a quarter of a million calls to compute a single number. Now letโs cache the results.
Memoization Using a Dictionary
Output:
75025
354224848179261915075Code language: Python (python)
Each value is calculated only once, so the function now makes about n calls instead of roughly 2n.
Note: This example uses a mutable default argument (memo={}) on purpose so the cache is shared between calls. In most other functions, a mutable default argument is a bug, so use this pattern only when you really want a shared cache.
Memoization Using functools.lru_cache
Python has memoization built in. Add the @lru_cache decorator from the functools module, and Python caches the results for you:
Output:
354224848179261915075
CacheInfo(hits=98, misses=101, maxsize=None, currsize=101)Code language: Python (python)
In Python 3.9 and later, you can also use @functools.cache, which is a shorter way of writing @lru_cache(maxsize=None). Keep in mind that the arguments of a cached function must be hashable, so you cannot pass a list directly.
Comparing the Speed
Output:
Without memoization: 0.0893 seconds
With memoization: 0.000018 secondsCode language: Python (python)
The exact times depend on your machine, but the memoized version is thousands of times faster, and the gap grows quickly as n increases.
Recursion vs Iteration
Any recursive function can be rewritten using a loop (iteration), and vice versa. Here is factorial written both ways:
Output:
720
720Code language: Python (python)
Both return the same result, but they behave differently:
| Aspect | Recursion | Iteration |
|---|---|---|
| How it repeats | Function calls itself | Loop (for / while) |
| Stop condition | Base case | Loop condition becomes false |
| Memory use | One stack frame per call | Constant (no extra frames) |
| Speed in Python | Slower, function calls have overhead | Usually faster |
| Depth limit | Limited by the recursion limit (1000 by default) | No such limit |
| Readability | Very clear for trees, nested data, divide and conquer | Clearer for simple, linear repetition |
| Risk | RecursionError if the base case is wrong | Infinite loop if the condition is wrong |
Converting a tail-recursive function to a loop: Because Python does not optimize tail calls, a common technique is to turn the accumulator into a variable and the recursive call into a loop step:
Output:
21
21Code language: Python (python)
When to Use Recursion
Recursion is a good choice when:
- The problem is naturally defined in terms of smaller versions of itself, such as factorial, GCD, or Fibonacci.
- You are working with hierarchical or nested data: trees, folder structures, nested lists, JSON, or HTML.
- You are using divide and conquer algorithms such as binary search, merge sort, and quick sort.
- You need backtracking, such as generating permutations and combinations, or solving mazes and Sudoku.
- The recursion depth stays small (well under the recursion limit).
Prefer a loop when:
- The task is a simple, linear repetition, like summing a list or counting.
- The input can be very large, so the recursion would go thousands of levels deep.
- Performance and memory usage are critical.
Advantages and Disadvantages of Recursion
Advantages
- Code is often shorter, cleaner, and closer to the mathematical definition of the problem.
- It handles nested and tree-like structures naturally, without managing your own stack.
- Complex problems like Tower of Hanoi and permutations become much easier to express.
Disadvantages
- Each call uses stack memory, so deep recursion uses more memory than a loop.
- Function calls in Python are relatively expensive, so recursion is usually slower.
- Python limits recursion depth and does not optimize tail calls.
- Recursive code can be harder to trace and debug for beginners.
Common Mistakes in Recursion
1. Missing or Unreachable Base Case
If the input never reaches the base case, the function recurses until it hits a RecursionError. In the example below, n skips over 0 when you start with an odd number:
Fix: Use a condition that catches every possible ending, such as if n <= 0:.
2. Forgetting to Return the Recursive Call
A very common bug is calling the function recursively but forgetting to return its result. The result is lost, and the function returns None.
Output:
NoneCode language: Python (python)
The base case does return 6, but only to the call one level above it, which then throws that value away. The outermost call reaches the end of the function and returns None. If the lost value is used in a calculation, such as n + func(n - 1), you will instead get a TypeError because Python cannot add a number and None.
Fix: Always write return gcd(b, a % b).
3. Not Making the Problem Smaller
Every recursive call must move closer to the base case. Calling factorial(n) instead of factorial(n - 1), or list_sum(numbers) instead of list_sum(numbers[1:]), causes infinite recursion.
4. Recomputing the Same Values
Tree recursion like the plain fibonacci() function repeats a huge amount of work. If your recursive function is slow and calls itself with the same arguments many times, add @lru_cache.
5. Using Recursion for Very Large Inputs
A recursive function that works for n = 100 may fail for n = 10000. If the depth depends directly on the input size, consider a loop or an explicit stack (a list you push to and pop from) instead.
Summary
- A recursive function is a function that calls itself to solve smaller versions of the same problem.
- Every recursive function needs a base case that stops the recursion and a recursive case that moves toward it.
- Python uses the call stack to track each call. Calls pile up while winding and are resolved in reverse order while unwinding.
- Common types are direct, indirect, tail, head, and tree recursion.
- Pythonโs default recursion limit is 1000. Exceeding it raises
RecursionError. Python does not optimize tail calls. - Use memoization (
@lru_cacheor a dictionary) to avoid repeating work in tree-recursive functions. - Use recursion for trees, nested data, divide and conquer, and backtracking. Use loops for simple repetition and very large inputs.
Recursion takes some practice before it feels natural. Start by tracing small examples on paper, always identify the base case first, and then check that every call makes the problem smaller. To keep practicing, try the Python Functions Exercises and test yourself with the Python Functions Quiz.

Leave a Reply