Depth, and when to loop instead
After this: Say what limits depth, and rewrite a recursion as a loop, with your own stack if it needs one.
On this page · 6 sections · 3 checks
You have seen that every call adds a frame to the call stack, and that a frame stays there until its call returns. Frames take up memory, so the stack cannot grow forever. How deep can a recursion go? And what do you do when the answer is "not deep enough"?
The limit
The depth of a recursion is the number of frames on the stack at the deepest moment. Python and Java both put a limit on it, but in different ways.
Python counts frames. By default it allows about 1,000 at once, and sys.getrecursionlimit() tells you the number. The call that would go past the limit raises a .
Java has no counter. Each thread has a stack of a fixed size, usually one or two megabytes on a modern computer. A thread is one running path through a program, and a small program has one main thread. When a new frame does not fit, Java throws a . The depth this allows depends on the size of each frame. For a small method it is tens of thousands of frames.
import sys
def depth(n): if n == 0: return 0 return 1 + depth(n - 1)
print(sys.getrecursionlimit()) # 1000 by defaultprint(depth(900)) # fitstry: depth(100_000) # does notexcept RecursionError as e: print("RecursionError:", e)1000 900 RecursionError: maximum recursion depth exceeded
static int depth(int n) { if (n == 0) return 0; return 1 + depth(n - 1);}
System.out.println(depth(900)); // fitstry { depth(10_000_000); // does not: the thread's stack runs out} catch (StackOverflowError e) { System.out.println("StackOverflowError");}900 StackOverflowError
Here is how to read it.
depth(n)calls itself n times, one call inside another, and returns n. It is a correct function.depth(900)fits within the limit in both languages.- The next call is much deeper. depth(100_000)depth(10_000_000) does not fit, so the code catches the error and prints its name.
The function has no bug here. The limit on frames is the problem. A loop that counts to the same number would add no frames at all.
Watch it happen
Watch the depth counter in both runs.
- factorial(8)Call factorial(8). There are nine frames at the deepest point. This depth counter is the number that Python limits to 1,000.
- countdown(8)
- empty
- no calls yet
Call a function to push its first frame.
- calls
- 0
- depth
- 0
Loop instead
Some recursions turn directly into a loop. This works when each frame makes one smaller call and has a small amount of work left over. factorial is one of these. Each frame multiplies on the way back, so a loop can do the same multiplications on the way forward.
def factorial_loop(n): result = 1 while n > 0: result *= n # what the frame for n did on the way back n -= 1 return result
print(factorial_loop(5))print(factorial_loop(0))120 1
static int factorialLoop(int n) { int result = 1; while (n > 0) { result *= n; // what the frame for n did on the way back n -= 1; } return result;}
System.out.println(factorialLoop(5));System.out.println(factorialLoop(0));120 1
Here is a run with n = 3.
| n at the start of the turn | result after multiplying |
|---|---|
| 3 | 3 |
| 2 | 6 |
| 1 | 6 |
Then n is 0, the loop stops, and the function returns 6. There is only ever one frame, so the depth does not grow with n.
Keeping your own stack
A plain loop is not enough when the recursion branches, or when a frame has to come back and carry on in the middle of something. The loop would lose its place. So you keep track of the work yourself, in a stack of your own. This is called an .
The simplest example is adding up a nested list, which is a list whose items can be lists too. [1, [2, 3, [4]], 5] has an inner list, and that list has another one inside it. The numbers add up to 15.
def total(items): result = 0 for x in items: if isinstance(x, list): result += total(x) # this frame remembers its place in the outer list else: result += x return result
def total_iterative(items): result = 0 stack = [items] # our own stack: lists still to visit while stack: current = stack.pop() for x in current: if isinstance(x, list): stack.append(x) # push instead of call else: result += x return result
nested = [1, [2, 3, [4]], 5]print(total(nested), total_iterative(nested))15 15
static int total(List<?> items) { int result = 0; for (Object x : items) { if (x instanceof List<?> inner) result += total(inner); // this frame remembers its place else result += (Integer) x; } return result;}
static int totalIterative(List<?> items) { int result = 0; Deque<List<?>> stack = new ArrayDeque<>(); // our own stack: lists still to visit stack.push(items); while (!stack.isEmpty()) { List<?> current = stack.pop(); for (Object x : current) { if (x instanceof List<?> inner) stack.push(inner); // push instead of call else result += (Integer) x; } } return result;}
List<?> nested = List.of(1, List.of(2, 3, List.of(4)), 5);System.out.println(total(nested) + " " + totalIterative(nested));15 15
The first function is the recursive version. When it meets an inner list, it calls itself on that list, and its frame remembers its place in the outer list.
The second function is the loop. stack starts with one list on it. Each turn of the loop pops a list and goes through its items. A number is added to result. An inner list is pushed on the stack to be visited on a later turn. That push is the highlighted line, and it sits where the recursive version made its call.
Here is the run, starting with the whole list on the stack.
- Pop
[1, [2, 3, [4]], 5]. Add 1, push[2, 3, [4]], add 5. The result is 6. - Pop
[2, 3, [4]]. Add 2 and 3, and push[4]. The result is 11. - Pop
[4]. Add 4. The result is 15. - The stack is empty, so the loop stops.
The stack holds the work still to do, which is the job the waiting frames did in the recursive version. It is an ordinary data structure in the program's main memory, which has far more room than the call stack. So the depth of nesting no longer matters.
Check yourself
depth is a correct function, and depth(100_000) needs 100,000 callsdepth(10_000_000) needs ten million calls, one inside another. What happens?
Here is factorial as a loop. In the recursive version, each frame multiplied by its n on the way back. Complete the line that does the same on the way forward.
def factorial_loop(n): result = 1 while n > 0: ______________________ # ← what the frame for n did on the way back n -= 1 return resultstatic int factorialLoop(int n) { int result = 1; while (n > 0) { ______________________ // ← what the frame for n did on the way back n -= 1; } return result;}total(items) adds up a list whose items can be lists too, nested to any depth. The input can be deep enough to reach the limit. What is the right way to rewrite it?
Connect
- State the limits: Python's recursion limit of 1,000 and RecursionError; Java's StackOverflowError when the thread's stack is full.
- Turn a recursion that makes one smaller call into a plain loop.
- Turn a branching or nested recursion into a loop with your own stack, which holds the work still to do.