debugModeratepending
Python RecursionError -- hitting the recursion limit
Viewed 0 times
RecursionErrorrecursion limitsetrecursionlimititerativestack overflowmemoize
python
Error Messages
Problem
Python raises RecursionError: maximum recursion depth exceeded. Recursive function works for small inputs but crashes for large ones.
Solution
(1) Check for infinite recursion: missing or wrong base case. (2) Python default recursion limit is 1000. Increase with sys.setrecursionlimit(10000) but this is a band-aid. (3) Convert to iterative: use explicit stack or loop. (4) Use functools.lru_cache for memoized recursion (reduces actual recursion depth). (5) For tree traversal: iterative with stack is always safer than recursive.
Why
Python does not optimize tail recursion. Each recursive call adds a stack frame. The limit exists to prevent stack overflow crashes, which would kill the process without a useful error message.
Revisions (0)
No revisions yet.