In programming, recursive functions are routines or methods that call themselves directly or indirectly. Python limits the number of times a recursion function can call itself. If the recursion function exceeds that limit, Python raises the error
RecursionError: maximum recursion depth exceeded while calling a Python object
.
This tutorial will discuss the above error in detail and help you learn to debug and resolve it. We will also walk through an example to understand this error.
So let's get started!
Python RecursionError: Maximum Recursion Depth Exceeded while Calling a Python Object
Recursion is a powerful technique to solve specific types of problems in programming. However, one must be very careful while dealing with recursive functions, as they may enter infinite loops.
Every recursive function has a base case that acts as a terminating condition. When a function meets the base case, it stops calling itself and returns the value back.
However, if the base case is not defined correctly or the recursive logic is incorrect, the function may end up calling itself infinitely. This means the function continues calling itself without any termination condition.
Calling any function occupies space in the memory. And calling a function inside a function for infinite times can occupy almost every part of your computer memory. To tackle this problem, Python has implemented a Recursion Depth limit.
According to the Python recursion depth limit, by default, a recursion function can all itself only 1000 times. If the recursion exceeds this limit, the interpreter throws the error
RecursionError: maximum recursion depth exceeded while calling a Python object
.
To know the default Recursion limit for your program, you can use the
getrecursionlimit()
method from the Python sys modules.
Example
import sys
print("This default recursion limit is :", sys.getrecursionlimit())
Output
This default recursion limit is : 1000
If we look at the recursion error statement, we can divide it into two parts
- RecursionError
- maximum recursion depth exceeded while calling a Python object
1. RecursionError
RecursionError is one of the Python standard exceptions. It is a module exception that comes under the Python RuntimeError. Python raises this exception when it detects a maximum recursion depth in a program.
2. maximum recursion depth exceeded while calling a Python object
The "
maximum recursion depth exceeded while calling a Python object
" statement is the error message that tags along with the RecursionError exception. This error message tells us that a Python function has exceeded the number of recursion calls.
Common Example Scenario
Let us write a Python program using recursion that prints the
nth
number from a Fibonacci series. You can even write this program using the for loop.
In the Fibonacci series , the first two numbers are 0 and 1; the following numbers are calculated with the sum of the previous two numbers.
Program
# recursive function to find the nth Fibonacci number
def n_fibonacci(n):
if n==0:
return 0
elif n==1:
return 1
else:
return n_fibonacci(n-1)+n_fibonacci(n-2)
#
n=10
print(f"The {n} st/nd/th Fibonacci number is: ",n_fibonacci(n-1))
Output
The 10 st/nd/th Fibonacci number is: 34
The above program is correct, and it also shows the correct output. But if we change the value of
n=10
to
n=1005
, it will raise the error.
Program
# recursive function to find the nth Fibonacci number
def n_fibonacci(n):
if n==0:
return 0
elif n==1:
return 1
else:
return n_fibonacci(n-1)+n_fibonacci(n-2)
#out of the recursion range
n=1005
print(f"The {n}st/nd/th Fibonacci number is: ",n_fibonacci(n-1))
Output
RecursionError: maximum recursion depth exceeded in comparison
You can see that we receive the RecursionError with a different Error message. This is because the error message changes according to the operation we perform inside the function.
Here, it displays
"
maximum recursion depth exceeded in comparison
".
This is because after exceeding the recursion limit, the Python interpreter can also not perform the comparison operator inside the recursion.
Solution
Python provides a
setrecursionlimit()
method that accepts an integer value as an argument and sets it as a recursion limit for the program. We can use this method to increase the default recursion depth limit.
Note:
The
setrecursionlimit()
method is also limited and can only increase the recursion limit depth to 3500.
To solve the above example, we can increase the recursion limit to 2000 using the
setrecursionlimit()
method.
Example
import sys
# increase the recursion limit
sys.setrecursionlimit(2000)
# recursive function to find the nth fibonacci number
def n_fibonacci(n):
if n==0:
return 0
elif n==1:
return 1
else:
return n_fibonacci(n-1)+n_fibonacci(n-2)
#now in recursion range
n=1005
print(f"the {n}st/nd/th fibonacci number is: ",n_fibonacci(n-1))
Output
the 1005 st/nd/th fibonacci number is: 482051511617926448416241857411039626258600330733909004920469712704382351844831823569922886993050824175326520025449797859766560885196970738202943545195859929088936259370887605815413541849563887924611727164704130
Executing the above program may take 10 to 20 minutes to finish because it calls the function repeatedly 2000 times.
Wrapping Up!
The
RecursionError
occurs when a recursion call exceeds the default recursion depth limit. When you encounter this error in your Python program, you must consider using an iterative approach to solve the problem. Using iterative statements like
for
and
while
loop, we can perform the desired action quickly and efficiently.
However, if you wish to solve your problem recursively, in that case, you can use them
setrecursivelimit()
to increase the default limit of the recursion call.
If you still get this error in your Python program, you can share your code in the comment section. We will try to help you with debugging.
People are also reading:
- Python FileNotFoundError: [Errno 2] No such file or directory Solution
- How to Remove Last Character from Python String?
- Python SyntaxError: non-default argument follows default argument Solution
- What is CubicWeb in Python?
- Python TypeError: cannot unpack non-iterable NoneType object Solution
- What is Python Pickle Module?
- Python IndentationError: expected an indented block Solution
- What is Web2Py in Python?
- Python NameError: name ‘self’ is not defined Solution
- What is TurboGears in Python?
Leave a Comment on this Post