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_cache or functools.cache avoids 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:

XKCD comic 1739: Fixing Problems
Image: xkcd.com

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 Python

Test your understanding of recursive thinking in Python, including base cases, recursive data structures, maintaining state, and caching results.

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:

Iterative Present Delivery

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:

Language: Python
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:

  1. Appoint an elf and give all the work to them.
  2. 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:

Recursive Present Delivery

Read the full article at https://realpython.com/python-thinking-recursively/ »


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]