Skip to content

How to Fix RecursionError: maximum recursion depth exceeded in Python

DodaTech Updated 2026-06-24 2 min read

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
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

  1. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  2. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  3. Using return to 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

### What is the default recursion limit in Python?

The default recursion limit is 1000. This prevents stack overflow crashes. You can check it with sys.getrecursionlimit() and change it with sys.setrecursionlimit(n).

Does Python optimize tail recursion?

No. Python does not implement tail call optimization. A tail-recursive function will still hit the recursion limit the same way as a non-tail-recursive one. Convert to iteration for deep recursion.

Can infinite loops cause RecursionError?

No. An infinite loop causes the program to hang indefinitely. RecursionError specifically comes from function calls piling up on the call stack. A loop uses constant stack space.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro