In Python, Recursion functions are those functions that call themself inside their function definition. Python limits the number of times a recursion function can call itself, and if the recursion function exceed that limit, Python raise the error
RecursionError: maximum recursion depth exceeded while calling a Python object
.
In this Python guide, we will discuss this error in detail and see learn how to debug it. We will also walk through an example in order to demonstrate this error. So let's get started with the Error statement.
Python RecursionError: Maximum Recursion Depth Exceeded while Calling a Python Object
Python supporters the concept of Recursion functions , in which a function can call itself, again and again, until a base condition gets satisfied or it encounters the return statement. If during the recursion process the base condition does not get satisfied or it could not find the return statement, the recursion function will act as an infinite loop.
But calling a 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 this Python recursion depth limit, by default, a recursion function can all itself only 1000 times. And if the recursion exceeds this limit the Python 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 Python sys modules
getrecursionlimit()
method.
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. This exception is raised in a Python program when the Python interpreter detects a maximum recursion depth.
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 is telling us that we a Python function has exceeded the specified or default recursion calls.
Common Example Scenario
Let's say you need to
write a program
in Python that prints the
nth
number from a Fibonacci series. And you need to write this Python program using recursion. Although this program can easily be created using for loop, but for now we are assuming you are learning recursion and this is your task. The first two numbers of the Fibonacci series are 0 and 1 and the next numbers in the series are calculated with the sum of its previous two numbers.
In the Python program we create there we take a number
n
that represent the n number of the Fibonacci series
Example
# 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 10st/nd/th fibonacci number is: 34
The above program is absolutely correct, and it also shows the correct output as well. But if we change the value from
n=10
to
n=1005
it will raise the Error.
Example Example
# 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
Here you can see that we are receiving the RecursionError with a different Error message, this is because the error message changes according to the operation we are performing inside the function.
Here it is showing
"
maximum recursion depth exceeded in comparison
"
because after exceeding the recursion limit the python interpreter is also not able to perform the comparison operator inside the recursion.
Solution
Python provide a
setrecursionlimit()
method that accepts an integer value as an argument and set it as a recursion limit for the program. We can use this method to increase the default depth limit of the recession for our program.
Note:
The
setrecursionlimit()
method is also limited and can only increse the recursion limit depth to 3500.
To solve the above example we can increase the limit of recursion to 2000 using the
setrecursionlimit()
method
Example Solution
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
When you execute the above program it may take 10 to 20 minutes to complete because calling a function again and again for 2000 times takes time.
Wrapping Up!
The
RecursionError
occur in a Python program when a recursion call exceeds the default or specified recursion depth limit. When you encounter this error in your Python program, the first thing you should consider is using an iterative approach to solve the problem. Because using iterative statements like
for
and
while
loop we can perform the iterative action quickly and efficiently.
If you have to solve your problem with a recursive way only, in that case, you can use the
setrecursivelimit()
to increase the default depth of the recursion call. If you are still getting this error in your python program, you can share your code in the comment section. We will try to help you in 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