TryBugHunt

RecursionError: maximum recursion depth exceeded

RecursionError: maximum recursion depth exceeded in Python means a function kept calling itself without reaching a stopping condition.

PythonPattern: Infinite loops

How do I fix RecursionError: maximum recursion depth exceeded?

To fix RecursionError: maximum recursion depth exceeded in Python, locate the line causing the error and check the values right before it runs. Most occurrences happen because of no base case. Apply a defensive check or safe fallback, make sure collections or objects exist before access, and verify return values from upstream functions.

1. Inspect bounds & typesPrint or inspect collection sizes and verify variables are not empty or None/undefined.
2. Guard with safe accessUse optional chaining (?.), dictionary get(), or guard conditions before dereferencing.
3. Trace upstream originsFind where the value was instantiated or returned rather than only patching the symptom.

What does RecursionError: maximum recursion depth exceeded mean?

Python caps the call stack at roughly 1000 frames to stop runaway recursion from exhausting memory. Hitting the cap almost always means the base case is missing, unreachable, or the recursive call is not moving toward it.

Why does RecursionError: maximum recursion depth exceeded happen?

1. No base case

Nothing stops the descent, so it runs until the stack limit.

Breaks

def countdown(n):
    print(n)
    countdown(n - 1)

Works

def countdown(n):
    if n <= 0:
        return
    print(n)
    countdown(n - 1)

2. The base case can be skipped

Testing == 0 misses it entirely if n starts negative or steps by more than one.

Breaks

def countdown(n):
    if n == 0:
        return
    countdown(n - 2)

Works

def countdown(n):
    if n <= 0:
        return
    countdown(n - 2)

3. The argument never changes

Recursing with the same value repeats forever.

Breaks

def walk(items):
    if not items:
        return
    walk(items)

Works

def walk(items):
    if not items:
        return
    walk(items[1:])

How to find it in your own code

Print the argument at the top of the function. If it is not moving toward the base case on every call, that is the bug. Use <= rather than == for the base case so it cannot be stepped over.

Try it: fix this bug

medium

factorial(5) crashes: RecursionError: maximum recursion depth exceeded.

def factorial(n):
    return n * factorial(n - 1)
Open with hintsRuns in your browser. No account needed.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Related error guides

View all infinite loops →