How To Fix RecursionError: maximum recursion depth exceeded in Python

Recursive functions are functions that call themselves during execution, the RecursionError: maximum recursion depth exceeded occurs because the recursive function you use has exceeded Python’s limits. This guide will show the cause of the error so you can fix it in your program.

Why does the error RecursionError: maximum recursion depth exceeded occur

A safe recursive function has bounds added to it to ensure they don’t execute infinitely. It means the function will stop when it finds an answer or a specific condition is met. An error will occur if you write a recursive function that crosses the limit in Python. Let’s see an example of the error in the example below.

Error Example:

An example of a recursive function counting numbers beyond the allowed limit of Python

def CountNumber(count):
count = count + 1

# Can't make recursion through 1000 times because the limit is exceeded
if count <= 1000:
print(count)

# CountNumber() function calls itself
CountNumber(count)

CountNumber(0)

Output:

RecursionError: maximum recursion depth exceeded

The error occurs because the number of executions of the recursive function has exceeded the 1000 times limit in Python, which is a Python mechanism to help the program avoid memory overflow. To solve this error, we will use the following solutions.

Solution For The RecursionError: maximum recursion depth exceeded

If Python does not have this protection, our program will execute until no memory is left. We can work around this error by using an alternate loop solution or increasing the recursion limit.

Use loop

We can change the function recursively by the loop to avoid the error.

Example:

def CountNumber(count):
# Use a For loop to replace a recursive function
for index in range(count, 1000):
print(index)

CountNumber(0)

Output:

0
…….
998
999

The error does not occur because we use a loop instead of a recursive function. But if you must use the recursive function, you can set the recursion number.

Using setrecursionlimit()

You can bypass Python’s default recursion limit by using the setrecursionlimit() method to set a new limit.

Example:

import sys

# Using the setrecursionlimit() method to set a new recursion limit.
sys.setrecursionlimit(2000)

def CountNumber(count):
count = count + 1
if count <= 1000:
print(count)
CountNumber(count)

CountNumber(0)

Output:

1
…….
998
1000

The error was fixed because we increased the recursion limit in Python to 2000

Summary

Through the article, we have understood the cause of the RecursionError: maximum recursion depth exceeded error in Python and the solutions to fix it. We often use an alternative loop because this is the best way. Hope you get the problem resolved soon.