Thinking Recursively in Python - Real Python
Thinking Recursively in Python
by Abhirag Awasthi Updated Dec 06, 2026 Reading time estimate 20m intermediate pythonTable of Contents
- Dear Pythonic Santa Claus...
- Recursive Functions in Python
- Maintaining State
- Recursive Data Structures in Python
- Naive Recursion Is Naive
- Pesky Details
- Conclusion
- References
- Frequently Asked Questions
Recommended Course
Thinking Recursively With Python (48m)
Problems (in life and also in computer science) can often seem big and scary. But if you keep chipping away at them, you can usually break them down into chunks small enough to solve directly. This is the essence of thinking recursively in Python , and my aim in this tutorial is to give you, my dear reader, the conceptual tools to approach problems from this recursive point of view.
By the end of this tutorial, you'll understand that:
- A recursive function calls itself and always combines a base case that stops the recursion with a recursive case that shrinks the problem.
- Each recursive call adds a stack frame to the call stack, and Python's default recursion limit is 1000 frames.
- You can maintain state during recursion by threading it through the arguments of each call or by keeping it in global scope .
- A recursive data structure , such as a list, is defined in terms of a smaller version of itself, and recursive functions naturally follow that shape.
- Decorating a recursive function with
functools.lru_cacheorfunctools.cacheavoids recomputing results that you've already calculated.
In this tutorial, you'll learn how to work with recursion in your Python programs by mastering concepts such as recursive functions and recursive data structures . You'll also learn about maintaining state during recursion and avoiding recomputation by caching results . This is going to be a lot of fun. Onwards and upwards!
Seymour Papert, the mathematician and educator who created the Logo programming language, captured the appeal of the topic in his book Mindstorms :
"Of all ideas I have introduced to children, recursion stands out as the one idea that is particularly able to evoke an excited response."
-- Seymour Papert, Mindstorms
Recursion also has a reputation for getting out of hand, which the xkcd comic Fixing Problems sums up nicely:
By the end of this tutorial, you'll know how to keep your own recursive functions from spiraling like that.
Take the Quiz: Test your knowledge with our interactive "Thinking Recursively in Python" quiz. You'll receive a score upon completion to help you track your learning progress:
Interactive Quiz
Thinking Recursively in PythonTest your understanding of recursive thinking in Python, including base cases, recursive data structures, maintaining state, and caching results.
Get Your Code: Click here to download the free sample code you'll use to trace recursive functions, threaded state, and cached Fibonacci calls.
Intermediate Python Deep Dive Live Course: Want to dig deeper into how Python functions work under the hood? Real Python's Intermediate Python Deep Dive live course covers functions, scoping, generators, and advanced data types with an instructor and a small cohort. Join the waitlist to hear about the next dates.
Dear Pythonic Santa Claus...
I realize that as fellow Pythonistas you're all consenting adults here, but children seem to grok the beauty of recursion better. So don't be an adult for a moment, and think about how you can use recursion to help Santa Claus.
Have you ever wondered how Christmas presents are delivered? I sure have, and I believe Santa Claus has a list of houses he loops through. He goes to a house, drops off the presents, eats the cookies and milk, and moves on to the next house on the list. Since this algorithm for delivering presents is based on an explicit loop construction, it's called an iterative algorithm. You can picture it as one long chain of deliveries:
Santa visits the houses one after the other, and the chain only ends when the list runs out. In Python, the iterative delivery algorithm needs nothing more than a for loop over the list of houses:
houses = ["Eric's house", "Kenny's house", "Kyle's house", "Stan's house"]
def deliver_presents_iteratively():
for house in houses:
print("Delivering presents to", house)
Calling the function delivers the presents to one house at a time, in list order:
Language: Python>>> deliver_presents_iteratively()
Delivering presents to Eric's house
Delivering presents to Kenny's house
Delivering presents to Kyle's house
Delivering presents to Stan's house
Each iteration of the loop handles exactly one house, and Santa does all the work himself.
But I feel for Santa. At his age, he shouldn't have to deliver all the presents by himself. I propose an algorithm with which he can divide the work of delivering presents among his elves:
- Appoint an elf and give all the work to them.
- Assign titles and responsibilities to the elves based on the number of houses for which they're responsible:
> 1: They're a manager and can appoint two elves and divide the work among them.= 1: They're a worker and have to deliver the presents to the house assigned to them.
Drawn out, the delegation forms a tree of elves, with the managers at the top and the workers at the bottom:
This is the typical structure of a recursive algorithm. If the current problem represents a simple case, solve it. If not, divide it into subproblems and apply the same strategy to them.
In Python, the recursive delivery algorithm mirrors that description, with each function call playing the part of one elf:
Language: Pythonhouses = ["Eric's house", "Kenny's house", "Kyle's house", "Stan's house"]
# Each function call represents an elf doing their work
def deliver_presents_recursively(houses):
# Worker elf doing their work
if len(houses) == 1:
house = houses[0]
print("Delivering presents to", house)
# Manager elf doing their work
else:
mid = len(houses) // 2
first_half = houses[:mid]
second_half = houses[mid:]
# Divides the work among two elves
deliver_presents_recursively(first_half)
deliver_presents_recursively(second_half)
This time, you pass the list of houses into the function, because every elf needs to know which houses they're responsible for:
Language: Python>>> deliver_presents_recursively(houses)
Delivering presents to Eric's house
Delivering presents to Kenny's house
Delivering presents to Kyle's house
Delivering presents to Stan's house
The output is identical to the iterative version, but no single call ever handles more than one house. Every manager elf splits the list in half and hands each half to another elf, and the worker elves at the bottom of the tree do the actual deliveries.
Remove adsRecursive Functions in Python
Now that you have some intuition about recursion, it's time for the formal definition of a recursive function. A recursive function is a function defined in terms of itself via self-referential expressions.
This means that the function will continue to call itself and repeat its behavior until some condition is met to return a result. All recursive functions share a common structure made up of two parts: base case and recursive case.
To demonstrate this structure, you'll write a recursive function for calculating n!, the factorial of n:
-
Decompose the original problem into simpler instances of the same problem. This is the recursive case:
n! = n x (n−1) x (n−2) x (n−3) ⋅⋅⋅⋅ x 3 x 2 x 1 n! = n x (n−1)! -
As the large problem is broken down into successively less complex ones, those subproblems must eventually become so simple that they can be solved without further subdivision. This is the base case:
n! = n x (n−1)! n! = n x (n−1) x (n−2)! n! = n x (n−1) x (n−2) x (n−3)! ⋅ ⋅ n! = n x (n−1) x (n−2) x (n−3) ⋅⋅⋅⋅ x 3! n! = n x (n−1) x (n−2) x (n−3) ⋅⋅⋅⋅ x 3 x 2! n! = n x (n−1) x (n−2) x (n−3) ⋅⋅⋅⋅ x 3 x 2 x 1!
Here, 1! is your base case, and it equals 1.
The recursive function for calculating n! follows exactly this two-part structure in Python:
def factorial_recursive(n):
# Base case: 1! = 1
if n == 1:
return 1
# Recursive case: n! = n * (n-1)!
else:
return n * factorial_recursive(n-1)
Calling it with 5 multiplies its way down to the base case and back:
>>> factorial_recursive(5)
120
Behind the scenes, each recursive call adds a stack frame (containing its execution context) to the call stack until you reach the base case. Then, the stack begins to unwind as each call returns its result:
Each colored box in the animation is one stack frame. Only when factorial_recursive(1) returns does factorial_recursive(2) get to finish its multiplication, and so on back up to the original call, which finally returns 120.
Note: Stopping at 1! means that factorial_recursive(0) never reaches the base case. Instead, n keeps decreasing into the negatives until Python gives up with a RecursionError , which you'll take a closer look at in the section on pesky details .
If you want 0! to come back as 1, which is how mathematicians define it, then make n == 0 your base case instead.
Maintaining State
When dealing with recursive functions, keep in mind that each recursive call has its own execution context, so to maintain state during recursion you have to either:
- Thread the state through each recursive call so that the current state is part of the current call's execution context
- Keep the state in global scope
A demonstration should make things clearer. Say you want to calculate 1 + 2 + 3 + ... + 10 using recursion. The state that you have to maintain is (current number you're adding, accumulated sum till now) .
Here's how you do that by threading it through each recursive call, meaning that you pass the updated current state to each recursive call as arguments :
Language: Pythondef sum_recursive(current_number, accumulated_sum):
# Base case
# Return the final state
if current_number == 11:
return accumulated_sum
# Recursive case
# Thread the state through the recursive call
else:
return sum_recursive(
current_number + 1, accumulated_sum + current_number
)
You kick off the recursion by passing in the initial state, which is the number 1 and an accumulated sum of 0:
>>> sum_recursive(1, 0)
55
The diagram below traces how the state flows from one call to the next until the base case returns the final state:
Each call receives the state, updates it, and hands it to the next call. Nothing needs to be stored between calls, because everything a call has to know arrives through its arguments.
Note: Threading two values through the calls is more machinery than this particular sum needs. You could write a one-argument sum_recursive(n) that returns n + sum_recursive(n - 1) and let the return values do the accumulating on the way back up.
The two-argument version is here because it makes the state explicit. That's the technique you'll want once the state is more than a running total.
Here's how you maintain the state by keeping it in global scope instead:
Language: Python# Global mutable state
current_number = 1
accumulated_sum = 0
def sum_recursive():
global current_number
global accumulated_sum
# Base case
if current_number == 11:
return accumulated_sum
# Recursive case
else:
accumulated_sum = accumulated_sum + current_number
current_number = current_number + 1
return sum_recursive()
Now the function takes no arguments at all, because the state lives outside of it:
Language: Python>>> sum_recursive()
55
The global statements tell Python to update the module-level variables instead of creating new local ones. Notice that this version also only works once. After the first call, current_number is stuck at 11, so any later call returns 55 straight away without doing any work.
I prefer threading the state through each recursive call because I find global mutable state to be evil, but that's a discussion for a later time.
Remove adsRecursive Data Structures in Python
A data structure is recursive if it can be defined in terms of a smaller version of itself. A list is an example of a recursive data structure. Let me demonstrate. Assume that you have only an empty list at your disposal, and the only operation you can perform on it attaches an element to the front:
Language: Python# Return a new list that is the result of
# adding element to the head (front) of input_list
def attach_head(element, input_list):
return [element] + input_list
Using the empty list and the attach_head operation, you can generate any list. For example, you can build [1, 46, -31, "hello"] from the inside out:
>>> attach_head(
... 1, attach_head(46, attach_head(-31, attach_head("hello", [])))
... )
[1, 46, -31, 'hello']
Python evaluates the innermost call first, so attach_head("hello", []) returns ["hello"], the next call out returns [-31, "hello"], then [46, -31, "hello"], and finally the full list. The animation below shows the list growing one head at a time:
Two observations follow from this little exercise:
-
Starting with an empty list, you can generate any list by recursively applying the
attach_headfunction, and thus the list data structure can be defined recursively as:+---- attach_head(element, smaller list) list = + +---- empty list -
Recursion can also be seen as self-referential function composition. You apply a function to an argument, then pass that result on as an argument to a second application of the same function, and so on. Repeatedly composing
attach_headwith itself is the same asattach_headcalling itself repeatedly.
List is not the only recursive data structure. Other examples include set , tree, dictionary , etc.
Recursive data structures and recursive functions go together like bread and butter. The recursive function's structure can often be modeled after the definition of the recursive data structure it takes as an input. You can see this by calculating the sum of all the elements of a list recursively:
Language: Pythondef list_sum_recursive(input_list):
# Base case
if input_list == []:
return 0
# Recursive case
# Decompose the list into its head and a smaller list,
# because a list is defined in terms of a smaller list
else:
head = input_list[0]
smaller_list = input_list[1:]
return head + list_sum_recursive(smaller_list)
Calling it on a short list gives you the sum of its elements:
Language: Python>>> list_sum_recursive([1, 2, 3])
6
The base case handles the empty list, and the recursive case peels off the head and recurses on the rest. The function has the same shape as the recursive definition of a list.
Naive Recursion Is Naive
The Fibonacci numbers were originally defined by the Italian mathematician Fibonacci in the thirteenth century to model the growth of rabbit populations. Fibonacci surmised that the number of pairs of rabbits born in a given year is equal to the number of pairs of rabbits born in each of the two previous years, starting from one pair of rabbits in the first year.
To count the number of rabbits born in the nth year, he defined the recurrence relation:
Fn = Fn-1 + Fn-2
The base cases are:
F0 = 0 and F1 = 1
A recursive function that follows this definition literally, with a print() call added so that you can watch every call happen, ends up doing a surprising amount of work:
def fibonacci_recursive(n):
print("Calculating F", "(", n, ")", sep="", end=", ")
# Base case
if n == 0:
return 0
elif n == 1:
return 1
# Recursive case
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
Even the fifth Fibonacci number takes fifteen calls to compute:
Language: Python>>> fibonacci_recursive(5)
Calculating F(5), Calculating F(4), Calculating F(3), Calculating F(2),
Calculating F(1), Calculating F(0), Calculating F(1), Calculating F(2),
Calculating F(1), Calculating F(0), Calculating F(3), Calculating F(2),
Calculating F(1), Calculating F(0), Calculating F(1), 5
The 5 at the very end is the return value. Naively following the recursive definition of the nth Fibonacci number was rather inefficient. As you can see from the output above, you're unnecessarily recomputing values. F(2) alone gets calculated three times. You can improve fibonacci_recursive by caching the results of each Fibonacci computation F k :
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci_recursive(n):
print("Calculating F", "(", n, ")", sep="", end=", ")
# Base case
if n == 0:
return 0
elif n == 1:
return 1
# Recursive case
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
Now every Fibonacci number gets calculated exactly once:
Language: Python>>> fibonacci_recursive(5)
Calculating F(5), Calculating F(4), Calculating F(3), Calculating F(2),
Calculating F(1), Calculating F(0), 5
lru_cache is a decorator from the functools module that caches the results. Thus, you avoid recomputation by explicitly checking for the value before trying to compute it. One thing to keep in mind about lru_cache is that since it uses a dictionary to cache results, the positional and keyword arguments (which serve as keys in that dictionary) to the function must be hashable .
If you're on Python 3.9 or newer, then you can also use functools.cache , which does the same job as lru_cache(maxsize=None) and saves you the maxsize argument. Since Python 3.8, @lru_cache also works without the parentheses.
Pesky Details
Python doesn't have support for tail-call elimination . As a result, you can cause a stack overflow if you end up using more stack frames than the default call stack depth :
Language: Python>>> import sys
>>> sys.getrecursionlimit()
1000
Keep this limitation in mind if you have a program that requires deep recursion. Remember factorial_recursive() and its base case of n == 1? Ask it for 0!, and it walks off into the negative numbers until Python pulls the plug:
>>> factorial_recursive(0)
Traceback (most recent call last):
...
RecursionError: maximum recursion depth exceeded
The same happens for a perfectly reasonable input like factorial_recursive(1001), because computing it takes more than a thousand nested calls. You can raise the limit with sys.setrecursionlimit(), but treat that as a last resort. If your problem routinely needs that many frames, then a loop is usually the better tool.
Note: Python 3.14 added a tail call interpreter to CPython as a build option, and since Python 3.15, the official Windows binaries use it by default. Despite the name, it's an internal implementation detail that uses tail calls between the C functions implementing Python's bytecode instructions. It doesn't eliminate a single Python stack frame for you, and the recursion limit applies exactly as before.
Also, Python's mutable data structures don't support structural sharing . If you treat them like immutable data structures, then you'll end up unnecessarily copying a lot of mutable objects, which is going to negatively affect your space and GC (garbage collection) efficiency. For example, I have used this pattern to decompose lists and recurse over them:
Language: Python>>> input_list = [1, 2, 3]
>>> head = input_list[0]
>>> tail = input_list[1:]
>>> print("head --", head)
head -- 1
>>> print("tail --", tail)
tail -- [2, 3]
I did that to simplify things for the sake of clarity. Keep in mind that tail is being created by copying. Recursively doing that over large lists can negatively affect your space and GC efficiency.
Conclusion
You've now seen recursion from two sides: as a way of thinking about problems, and as a handful of concrete techniques for writing recursive functions in Python.
In this tutorial, you've learned how to:
- Tell an iterative algorithm from a recursive algorithm by looking at how it repeats its work
- Structure a recursive function around a base case and a recursive case
- Follow each recursive call onto the call stack and watch the stack unwind again
- Maintain state by threading it through arguments or by keeping it in global scope
- Model a recursive function after the recursive data structure it consumes
- Avoid recomputation with
lru_cacheorcachefromfunctools - Respect Python's recursion limit and the cost of copying lists
I was once asked to explain recursion in an interview. I took a sheet of paper and wrote Please turn over on both sides. The interviewer didn't get the joke, but now that you've read this tutorial, hopefully you do 🙂 Happy Pythoning!
References
If you'd like to go deeper into recursive thinking, then these are the books that shaped this tutorial:
- Thinking Recursively
- The Little Schemer
- Concepts, Techniques, and Models of Computer Programming
- The Algorithm Design Manual
- Haskell Programming from First Principles
Get Your Code: Click here to download the free sample code you'll use to trace recursive functions, threaded state, and cached Fibonacci calls.
Frequently Asked Questions
Now that you have some experience with thinking recursively in Python, you can use the questions and answers below to check your understanding and recap what you've learned.
These FAQs are related to the most important concepts you've covered in this tutorial. Click the Show/Hide toggle beside each question to reveal the answer.
Thinking recursively means breaking a problem into smaller instances of the same problem until you reach a case that you can solve directly. In Python, you express that idea with a function that calls itself on the smaller instances and combines their results.
The base case is the input that the function can answer on the spot without calling itself again, and the recursive case breaks the input down and calls the function on the smaller piece. Every recursive function needs both, or the calls never stop.
Each recursive call adds a frame to the call stack, and Python stops you once you exceed its recursion limit, which defaults to 1000 frames. You hit this error either because your base case is missing or unreachable, or because your input needs more nested calls than the limit allows.
Decorate the function with lru_cache or cache from the functools module so that Python stores each result and returns it the next time the function gets called with the same arguments. Because the cache is a dictionary keyed by the arguments, those arguments must be hashable.
Recursion fits best when the data itself is recursive, such as a list defined as an element attached to a smaller list, or a tree, because the function can mirror the structure of the data. For deep or performance-sensitive work, a loop is often the better choice, since Python doesn't eliminate tail calls and every recursive call costs a stack frame.
Take the Quiz: Test your knowledge with our interactive "Thinking Recursively in Python" quiz. You'll receive a score upon completion to help you track your learning progress:
Interactive Quiz
Thinking Recursively in PythonTest your understanding of recursive thinking in Python, including base cases, recursive data structures, maintaining state, and caching results.
Liked it (thumbs up) Disliked it (thumbs down)Recommended Course
Thinking Recursively With Python (48m)
🐍 Python Tricks 💌
Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.
About Abhirag Awasthi
Programmer/Musician, constantly trying to create something worthwhile, getting better at my craft in the process
» More about AbhiragEach tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:
Aldren
Dan
Joanna
Martin
Master Real-World Python Skills With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
Master Real-World Python Skills
With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
Keep Learning
Related Topics: intermediate python
Related Learning Paths:
Related Courses:
Related Tutorials: