Have you ever seen those Russian dolls, where one doll opens to reveal a smaller one inside, and then another smaller one, and so on? Recursion in programming is a bit like that. It’s when a function calls itself to solve a smaller piece of the problem until it reaches the simplest version, which can be solved directly.
Let’s take a simple real-world example: printing a list of names from last to first.
# Recursive function to print names in reverse order
def print_names_reverse(names, index):
# Base case: stop when we reach the beginning
if index < 0:
return
# Print the current name
print(names[index])
# Recursive call: move to the previous name
print_names_reverse(names, index - 1)
# Sample list
names_list = ["Alice", "Bob", "Charlie", "Diana"]
# Start recursion from the last index
print_names_reverse(names_list, len(names_list) - 1)
How it works step by step:
We start at the last name (“Diana”).
The function prints it, then calls itself for the previous name.
This keeps happening until we reach the first name.
Once the first name is printed, the function stops — this stopping point is called the base case.
Notice how the function keeps calling itself, but each time it’s a slightly smaller problem. That’s recursion in its simplest form.
Recursion can look magical, but it’s all about breaking a problem into smaller pieces. Once you get the hang of it, you’ll see it’s a very natural way to solve problems — especially ones that repeat themselves.
Sometimes, recursion can end up repeating the same work for different parts of a problem. This is where a concept called memoization comes in — it’s a clever way to remember results so you don’t redo work unnecessarily.
Curious about making recursion super efficient and avoiding repeated work? Check out my Medium article on recursion with memoization
to see the next level in action! (Free link attached for you)