Skip to content

RecursionError: maximum recursion depth exceeded

Error message

                maximum recursion depth exceeded
              

Quick summary

Your recursive function exceeded Python's maximum call stack depth (default ~1000), usually due to missing or incorrect base case.

Why this happens

  • Missing base case — the recursion never stops

  • Base case condition is never reached

  • Recursion depth is genuinely too deep for the problem

  • Accidental infinite recursion (function calls itself with same args)

Minimal example

✗ Broken code
def countdown(n):
    print(n)
    countdown(n - 1)  # No base case!

countdown(5)  # RecursionError
✓ Fixed code
def countdown(n):
    if n < 0:  # Base case
        return
    print(n)
    countdown(n - 1)

countdown(5)

The original has no base case, so it recurses forever. Adding 'if n < 0: return' stops the recursion.

How to diagnose

  • Check that the base case is correct and reachable

  • Print the arguments at each call to see if they progress

  • Increase the limit with sys.setrecursionlimit() (temporary fix)

How to fix

  • Add or fix the base case so recursion terminates

  • Convert the recursive function to an iterative one

  • Use sys.setrecursionlimit() if the depth is legitimately high

How to prevent

  • Always define a correct base case before the recursive case

  • Prefer iteration for simple loops (Python isn't optimized for recursion)

  • Test with small inputs first

Related Resources

Related Glossary

Related Lessons

← Back to language