Recursion means a function calls itself to solve a smaller version of the same problem.
Every recursive function needs a base case that stops the calls and a recursive step that moves closer to that base case.
Use recursion for naturally nested problems. Use loops when the problem is simply repeating over a flat sequence.
The base case is the condition that returns an answer without calling the function again.
def countdown(number):
if number == 0:
return
print(number)
countdown(number - 1)
countdown(3)
3
2
1
When number reaches 0, the function returns instead of making another recursive call.
The recursive step calls the same function with a smaller or simpler input.
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5))
120
factorial(5) waits for factorial(4), and each smaller call eventually reaches factorial(0).
Each recursive call waits on the call stack. Too many nested calls can hit Python recursion limits.
Recursion fits nested structures because each item can be handled with the same rule.
def flatten(items):
result = []
for item in items:
if isinstance(item, list):
result.extend(flatten(item))
else:
result.append(item)
return result
print(flatten([1, [2, 3], [4, [5]]]))
[1, 2, 3, 4, 5]
The same flatten() function is reused whenever another list appears inside the data.
Try this next
0 of 2 completed
The function kept calling itself too many times, usually because the base case was missing or never reached.
Usually not in beginner Python. Choose recursion for clarity with nested problems, not for speed.
Print the input at the start of the function and test the smallest possible input before larger cases.
Explore 500+ free tutorials across 20+ languages and frameworks.