RecursionError: maximum recursion depth exceeded
RecursionError: maximum recursion depth exceeded in Python means a function kept calling itself without reaching a stopping condition.
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.
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
mediumfactorial(5) crashes: RecursionError: maximum recursion depth exceeded.
def factorial(n):
return n * factorial(n - 1)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.