RuntimeError 'maximum recursion depth exceeded'

Gerrit Holl gerrit at
Sun Nov 16 10:28:21 CET 2003

Georgy Pruss wrote:
> Sometimes I get this error.
> E.g.
> >>> sum = lambda n: n<=1 or n+sum(n-1) # just to illustrate the error
> >>> sum(999)
> 499500
> >>> sum(1000)
> ...........
> RuntimeError: maximum recursion depth exceeded
> Is there any way to set a bigger stack in Python?

Yes, use sys.setrecursionlimit()
See :

    Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.

    The highest possible limit is platform-dependent. A user may need to set the limit higher when she has a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash. 

Note that in this case, you can simlpy use the builtin sum:
See :

sum(sequence[, start])
    Sums start and the items of a sequence, from left to right, and returns the total. start defaults to 0. The sequence's items are normally numbers, and are not allowed to be strings. The fast, correct way to concatenate sequence of strings is by calling ''.join(sequence). Note that sum(range(n), m) is equivalent to reduce(operator.add, range(n), m) New in version 2.3. 

...but I assume you already knew the latter, since you said that you example
was just to illustrate the error. Just to be sure.


This space intentionally left blank.
Asperger Syndroom - een persoonlijke benadering:
Kom in verzet tegen dit kabinet:

More information about the Python-list mailing list