Deeper than Python's recursion limit: keep your own stack
Every recursive walk above has a limit, and a deep tree finds it.
| A chain, run from a script | size with sum(...) | size with a for loop |
|---|---|---|
| frames per level | 2: the call and its generator | 1 |
| frames at the deepest call | 1 + 2 × 499 = 999 | 1 + 999 = 1,000 |
| regions that fit | 499, and 500 don't | 999, and 1,000 don't |
Each call that hasn't returned yet holds a frame on the call stack. Python's recursion limit caps how many frames can be in use at once. The docs call it the maximum depth of the Python interpreter stack. The default is 1,000, and going past it raises RecursionError.
A chain is the deep case: its height is . Run from a script, size as written above raised RecursionError: maximum recursion depth exceeded at 500 regions. With a plain for loop in place of sum(...), it reached 999.
The generator expression inside sum runs in a frame of its own, and the script's top level, <module>, takes one more. In a notebook or a test runner, more frames are in use before your code starts, so the numbers can come out lower.