How to Fix RecursionError: maximum recursion depth exceeded in Python
In this tutorial, you'll learn about How to Fix RecursionError: maximum Recursion depth exceeded in Python. We cover key concepts, practical examples, and best practices.
Python raises RecursionError: maximum recursion depth exceeded when a recursive function recurses deeper than the configured limit (default 1000).
The Wrong Way
def factorial(n):
return n * factorial(n - 1) # missing base case
print(factorial(5))
This produces:
Traceback (most recent call last):
File "script.py", line 4, in <module>
print(factorial(5))
File "script.py", line 2, in factorial
return n * factorial(n - 1)
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
The Right Way
Include a base case that stops recursion:
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
Output:
120
Step-by-Step Fix
1. Add a proper base case
Every recursive function must have at least one base case that returns without recursing:
def countdown(n):
if n <= 0:
print("Done")
return
print(n)
countdown(n - 1)
countdown(3)
Output:
3
2
1
Done
2. Convert recursion to iteration
def factorial_iterative(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
print(factorial_iterative(5))
Output:
120
3. Increase the recursion limit (not recommended)
import sys
sys.setrecursionlimit(5000)
def deep_recursion(n):
if n <= 0:
return 0
return 1 + deep_recursion(n - 1)
print(deep_recursion(2000))
4. Use tail recursion optimization (via manual trampoline)
def trampoline(f, *args):
result = f(*args)
while callable(result):
result = result()
return result
Prevention Tips
- Always define base cases first when writing recursive functions.
- Prefer iterative solutions for deep recursion (over 500 levels).
- Set
sys.setrecursionlimit()only as a last resort. - Use stack data structures manually instead of the call stack.
- Test recursive functions with small inputs first.
Common Mistakes with recursionerror
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro