9/36
Part 2 of 8 · RecursionLearn

A list of the lists still to read replaces the recursion

Ask what each recursive call remembers. Here it's only the list it still has to read. So keep a list of the lists waiting to be read:

def total(nested):
    s, stack = 0, [nested]
    while stack:
        for item in stack.pop():
            if isinstance(item, list):
                # where the recursion called total(item)
                stack.append(item)
            else:
                s += item
    return s


print(total([1, [2, 3], [4, [5]]]))
print(total(nest(100_000)))
15
100000
Predict

The stack version pops a list, adds its numbers and pushes its sublists. In what order does it add the items of [1, [2, 3], [4, [5]]]?

Pick an answer above to see the rest