Fixing error – maximum recursion depth reached

Hi there folks. In this post I am going to teach you how to increase the recursion depth in python. Most of us at some time get this error :

RuntimeError: maximum recursion depth exceeded

If you want to fix this error just increase the default recursion depth limit but how to do it ? Just import the sys module in your script and in the beginning of the script type this :


This will increase the default limit to 1500. For the record the default limit is 1000. I hope that you found this post useful. Do share this on facebook and twitter and stay tuned for our next post.

3 thoughts on “Fixing error – maximum recursion depth reached”

  1. That’s a band-aid though. Instead of going into these crazy-deep (at least for Python, it would be another story in LISP or Haskell) recursions, you should rewrite your algorithm to an iterative one. If it is tail-recursive, a loop will suffice. In other cases, you can simply keep a list of tasks. For example, instead of

    def fib(x):
    if x < 2: return x
    return fib(x-1) + fib(x-2)

    you can write it iteratively like

    import collections
    def fib(x):
    tasks = collections.deque([x])
    res = 0
    while tasks:
    v = tasks.pop()
    if v < 2:
    res += v
    return res

    As you can see, the iterative variant is quite messy, but it makes the state explicit. (Full code at )

  2. Thank you for that. I had a perfectly working algorithm that required deeper stack to handle longer input. this worked – thanks again

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s