Skip to content
Craft

Why do I get maximum recursion depth exceeded

Seeing maximum recursion depth exceeded in Python means your calls nested past the interpreter's cap of 1000, from a missing base case or a genuinely deep input. Here is how to tell which, and the four fixes that actually work.

You get maximum recursion depth exceeded in Python because the interpreter caps nested function calls at 1000 by default, and your recursion went deeper than that, usually because the input is large or the base case is never reached. Fix it by checking the base case first, then converting the recursion to a loop with an explicit stack.

What does maximum recursion depth exceeded actually mean?

It means Python counted more than sys.getrecursionlimit() active calls (1000 unless you changed it) and raised a RecursionError instead of letting the call stack grow further. Nothing is wrong with the function's logic as such; the interpreter simply refused to go deeper.

The framing I find most useful is that the limit is a circuit breaker, not a wall. In a house, the breaker in the panel trips at 15 amps long before the wire in the wall melts. It is set conservatively on purpose, and you are allowed to swap it for a bigger one. But the wire is still the wire. The wire here is the memory your process has for call frames, and a bigger breaker only helps until you reach what the wire can carry.

Each call needs somewhere to live: a frame holding the arguments, the local variables, and the place to resume when the call returns. Until Python 3.10, every Python-level call also consumed space on the C stack, because the interpreter itself recursed in C. Overflow that and the whole process dies with a segmentation fault and no traceback. The recursion limit exists so that you get a catchable exception instead. From 3.11 onward, calls from Python code to Python code no longer use the C stack in the same way, but the counter and its default of 1000 stayed as a safety net, and some paths (recursive repr, deeply nested JSON, calls through C extensions) still hit a separate C-level limit.

So the error has exactly two possible causes, and the fix depends entirely on which one you have. Either the recursion is supposed to stop and never does, or it is supposed to go that deep and 1000 is too small.

Is it a bug in my base case or a genuinely deep input?

Run the function on a tiny input. If it fails on an input of size 5, you have a bug; if it works on 5 and 500 and fails somewhere past 990, you have a deep input. That one experiment separates the two causes in under a minute.

The classic bug looks like this:

def countdown(n):
    if n == 0:
        return
    countdown(n - 1)

countdown(-1)   # never reaches 0, RecursionError

The base case is correct for the inputs the author imagined and wrong for the one that arrived. Other common versions: a recursive call that passes the same argument it received, a graph traversal with no visited set so it walks a cycle forever, and an off-by-one where the base case tests n == 1 but the recursion steps by 2 and skips it. If the stack trace shows the same two or three lines repeating with arguments that are not changing in the direction you expect, stop reading about limits and fix the logic.

The second cause is subtler, because the code is correct. The question to ask is: what quantity is the depth equal to? You should be able to name it. For recursion over a list it is the length. For a tree it is the height. For a graph traversal it is the longest simple path the DFS happens to follow. For divide and conquer that halves the input it is about log n, which is almost never a problem: 1,000,000 elements need roughly 20 levels.

The trap is the tree height. A balanced binary tree with 1,000,000 nodes has height near 20. The same million nodes inserted into an unbalanced binary search tree in sorted order form a chain of height 1,000,000. The code did not change; the input shape did. The same applies to quicksort with a poor pivot on already-sorted data, where depth degrades from log n to n. If you want the underlying reasoning for why depth tracks structure rather than code, recursion as induction lays out how each call relies on a smaller instance of the same problem, and the size of that chain is the depth.

Should I just raise the limit with sys.setrecursionlimit?

Sometimes, but only if you know your maximum depth and it is modest. sys.setrecursionlimit(10000) is a reasonable fix for a depth of a few thousand. Setting it to 10**6 and hoping is how you trade a clean exception for a crashed interpreter.

The arithmetic is the reason. A typical Linux main thread has an 8 MB stack. On older CPython versions each nested Python call may use somewhere between a few hundred bytes and a kilobyte or more of C stack depending on the function. Divide 8 MB by that and the real ceiling lands in the tens of thousands of frames, not the millions. Past it, you do not get RecursionError; you get a segfault, and the limit you raised is precisely what disabled the guard that would have told you. Newer versions have more headroom for pure-Python recursion, and frame objects still cost heap memory, but I would not design around the exact numbers.

There is a second trick: run the work in a thread with a larger stack.

import sys, threading

sys.setrecursionlimit(10**6)
threading.stack_size(256 * 1024 * 1024)

t = threading.Thread(target=main)
t.start()
t.join()

This is common in competitive programming and it works. I treat it as a tool for a one-off script or a timed contest, not for code someone else will maintain. It hides a structural problem behind a 256 MB reservation, and it behaves differently on every operating system. In an interview, mentioning that you know it exists is fine; writing it as your answer usually signals that you reached for the shortcut instead of reshaping the algorithm.

How do I convert a deep recursion into an explicit stack?

Replace the call stack with a list you manage yourself: push the work you would have recursed into, pop one item per loop iteration, and push its children. The depth then lives on the heap, where a list can hold millions of entries, instead of in the frame counter.

Here is the case where I hit this most often. Take a 1000 by 1000 grid that is entirely land (1,000,000 cells) and run a flood fill from one corner, the same core move as Number of Islands. A recursive version visits neighbours in a fixed order, say down, up, right, left. On an open grid, that order can snake through the grid and keep recursing before it ever backs out, so the depth can approach the full million cells. At the default limit of 1000, it fails after roughly the first column. Even at a raised limit of 100,000 it fails, and at 10**6 it risks the segfault from the previous section.

The iterative version:

def flood(grid, r, c):
    rows, cols = len(grid), len(grid[0])
    grid[r][c] = 0
    stack = [(r, c)]
    size = 0
    while stack:
        r, c = stack.pop()
        size += 1
        for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            nr, nc = r + dr, c + dc
            if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
                grid[nr][nc] = 0   # mark on push, not on pop
                stack.append((nr, nc))
    return size

Count the work. Every cell is pushed once and popped once, so 1,000,000 pops. Each pop checks 4 neighbours, so 4,000,000 bounds-and-value checks. That is linear in the number of cells, the same as the recursive version would be, and on a laptop CPython finishes it in roughly one to two seconds. Space is the stack itself. In the worst case it holds on the order of the number of cells; a tuple of two small ints costs around 56 bytes, so even a pessimistic bound of one million entries is tens of megabytes, and the real peak is much lower because most cells are popped soon after they are pushed. Compare that with a frame per cell, which would be far heavier.

Two details matter. First, mark a cell visited when you push it, not when you pop it. Otherwise the same cell can be pushed by several neighbours before it is processed, and your stack grows to roughly four times the cell count for no reason. Second, visit order changes. A pop-based loop explores the last neighbour pushed first, which is the mirror of the recursive order. For flood fill and reachability that is irrelevant. For tasks that need post-order, such as computing subtree sizes or heights, push a pair like (node, False), and when you pop it, push (node, True) followed by the children. When you pop the True entry, all children are done, and you do the combine step there. That small flag is the whole translation of "the code after the recursive call".

The same idea handles the other textbook victim, a recursive sum over a linked list of 5,000 nodes. A while node: loop with an accumulator uses constant space and has no limit at all. If the recursion was tail-shaped (the recursive call is the last thing it does), a loop is a mechanical rewrite. Python will not do it for you, because it does not perform tail-call elimination, so a tail-recursive function still costs one frame per step. There is more on the cost side of this trade in is recursion slower than iteration.

How do I fix maximum recursion depth in top-down dynamic programming?

Either fill the table bottom-up in a loop, or warm the memo cache in small steps so no single call recurses deeply. Both keep the same recurrence and the same complexity; they only change the order in which states get computed.

Take a recurrence where f(n) depends on f(n - 1) and f(n - 2), decorated with functools.lru_cache. Call f(5000) cold and the first call descends 5,000 levels before anything is cached, which fails at the default limit. The total work is only about 5,000 states at constant cost each; the problem is purely the shape of the first descent.

The bottom-up fix is a plain loop from 0 to n, filling an array (or just two variables, since only the last two values are needed). That is tabulation, and the trade-offs between it and top-down are covered in memoisation versus tabulation.

The warm-up fix keeps your top-down code untouched:

for i in range(0, n + 1, 500):
    f(i)
result = f(n)

Calling f(0), then f(500), then f(1000) and so on means each call only has to reach back about 500 levels, because everything below the previous milestone is already cached. Maximum depth is about 500 instead of 5,000, and the total number of states computed is still 5,000. It is slightly ugly, and I would only use it when the recurrence is awkward to invert, such as a state with several dimensions or irregular dependencies. For a straightforward one-dimensional recurrence, write the loop.

Which fix should I choose?

Choose by how deep you need to go and who will read the code. Under a few thousand levels, raise the limit. Beyond that, restructure. The table puts the options side by side, with depths as rough guides for CPython on a typical Linux machine.

ApproachPractical depthExtra memoryEffortBest for
Default limit (1000)About 990 usableNoneNoneLog-depth divide and conquer
Raise setrecursionlimitA few thousand, up to low tens of thousands before crash riskOne frame per levelOne lineKnown, modest depth; scripts
Bigger thread stackHundreds of thousandsReserved stack (e.g. 256 MB)A few linesContests, one-off tools
Explicit stack (list)Limited by heap, millionsOne small tuple per pending itemModerate rewriteDFS, tree walks, flood fill
Bottom-up DP loopNo recursionTable, often reducible to O(1) rowsRe-derive the orderLinear and grid recurrences
Warm the memo in stepsStep size (e.g. 500)The memo, as beforeTwo linesAwkward top-down states

My own default is blunt. If the depth is bounded by something small and obvious, such as the height of a balanced tree or the number of digits in an integer, leave the recursion alone and enjoy how readable it is. If the depth is bounded by the input size n and n can reach 10^5 or more, I write the loop from the start, because the day the input grows is always the day the on-call phone rings.

Do other languages have the same recursion problem?

Yes, with different failure modes. Every mainstream language keeps call frames on a finite stack, and the difference is in how it fails and how much room you get.

Java throws StackOverflowError at roughly ten to twenty thousand frames with default settings, and you can raise the thread stack size with a flag. JavaScript engines allow somewhere around ten thousand frames and throw a RangeError. C and C++ do not guard anything: deep recursion just corrupts or crashes, typically a segfault at a depth set by the stack size and the frame size. Go grows goroutine stacks dynamically up to a large maximum, so it tolerates much deeper recursion, and some functional languages guarantee tail-call elimination so that tail-recursive loops use constant stack.

Python's 1000 is therefore on the low side, but it is not an outlier in kind. The lesson transfers: know what quantity your depth equals, and when that quantity can scale with the input, hold the pending work in a data structure instead of in the call stack.

Frequently asked questions

Is it safe to set the recursion limit to 10**6 in Python?

Not reliably. Past a certain depth, which depends on the Python version, the function, and the thread's stack size, the process can crash with a segmentation fault instead of raising an exception. Raise the limit only to a depth you have measured, or restructure the code.

Why does my recursive function work in an online judge but fail on my machine?

Judges often raise the recursion limit, run with a larger stack, or use a different interpreter version with different stack behaviour. Your local interpreter uses the default of 1000 unless the code sets otherwise. Printing sys.getrecursionlimit() in both places usually explains the gap.

Does Python optimise tail recursion?

No. Python never eliminates tail calls, so a tail-recursive function still uses one frame per call and hits the same limit as any other recursion. If the recursion is tail-shaped, rewrite it as a loop; the transformation is mechanical.

To practise the explicit-stack rewrite on a problem where the recursive version genuinely breaks, take the flood fill from this essay and try Number of Islands on a grid large enough to defeat the default limit