8/36
Part 2 of 8 · RecursionLearn and do

Each recursive call adds a frame, and Python's default limit is 1,000

A function that calls itself pushes one more frame per call. Sum a nested list that way:

def total(nested):
    s = 0
    for item in nested:
        if isinstance(item, list):
            s += total(item)
        else:
            s += item
    return s


# [1, [1, [1, ...]]], depth lists deep
def nest(depth):
    nested = [1]
    for _ in range(depth - 1):
        nested = [1, nested]
    return nested


print(nest(3))
print(total(nest(3)))
[1, [1, [1]]]
3

Follow one run. traced is total with two prints: a line when a call starts and a line when it returns, indented one step for each level d:

def traced(nested, d=0):
    pad = "    " * d
    print(f"{pad}call on {nested}")
    s = 0
    for item in nested:
        if isinstance(item, list):
            s += traced(item, d + 1)
        else:
            s += item
    print(f"{pad}return {s}")
    return s


traced([1, [2, [3]]])
call on [1, [2, [3]]]
    call on [2, [3]]
        call on [3]
        return 3
    return 5
return 6

On the way down, each call adds the numbers it holds until it meets an inner list, then calls total on that list and waits. The outer call has s = 1 when it calls total([2, [3]]). That call has s = 2 when it calls total([3]). Each waiting call keeps its own s in its own frame.

On the way back up, total([3]) returns 3. The middle call adds it to its 2 and returns 5. The outer call adds the 5 to its 1 and returns 6.

The frames of total([1, [2, [3]]]), with each one's s
outer s=1
call [1, [2, [3]]]
outer s=1middle s=2
call [2, [3]]
outer s=1middle s=2inner s=3
call [3]
outer s=1middle s=5
inner returns 3
outer s=6
middle returns 5
emptyouter returns 6the answer

One frame for each level of nesting. The stack is deepest at the innermost list.

Python caps how many frames there can be. sys.getrecursionlimit() returns that cap, which its docs call the maximum depth of the Python interpreter stack. It's 1,000 by default.

Called from a script's top level, total(nest(999)) returned 999, and total(nest(1000)) raised RecursionError: maximum recursion depth exceeded. Here are the two stacks at their deepest:

total(nest(999))total(nest(1000))
frame 1<module><module>
frames 2 and uptotal, calls 1 to 999total, calls 1 to 1,000
in all1,000 frames: it fits1,001 frames: RecursionError

The script's own module frame was already on the stack. So 999 calls of total filled all 1,000 frames, and the 1,000th call was one too many.

At depth 5,000 the traceback was only 14 lines long. Python folds the repeats into one line: [Previous line repeated 996 more times].

In the editor, write depth(nested) with recursion, the way total walks: how many lists deep a nested list goes. Then write fits(levels): whether a recursive walk that many levels deep, called from a script's top level, stays within 1,000 frames. nest is the helper from above.