Iterative Flatten Nested Lists

Flatten arbitrarily nested lists with an explicit iterator stack, so a thousand levels deep still works where recursion would hit its limit.

PythonData Integrity

Code

pythonsnippet
26 lines
def flatten(nested):
    """Drain an iterator stack level by level — no recursion depth limit."""
    flat = []
    stack = [iter(nested)]
    while stack:
        try:
            item = next(stack[-1])
        except StopIteration:
            stack.pop()
            continue
        if isinstance(item, list):
            stack.append(iter(item))
        else:
            flat.append(item)
    return flat

deep = [1, [2, [3, [4, [5]]]], 6, [], [7, [8]]]
print("flat:", flatten(deep))
print("order kept:", flatten(deep) == [1, 2, 3, 4, 5, 6, 7, 8])
print("empty levels vanish:", flatten([[], [[]], [1, []]]))

# a thousand nested levels would hit the recursion limit; the stack does not
very_deep = [1]
for _ in range(1000):
    very_deep = [very_deep]
print("depth 1000 ok:", flatten(very_deep) == [1])

Output

Captured from a sandboxed run of this snippet in the build pipeline.

flat: [1, 2, 3, 4, 5, 6, 7, 8]
order kept: True
empty levels vanish: [1]
depth 1000 ok: True

Execution shape

Iterative Flatten Nested Lists keeps everything in the function flatten.

Repetition is confined to while stack — the rest of the file is straight-line.

What to watch for

  • There is nothing to declare: the runtime ships every API this file touches.

Using it

Signature: def flatten(nested)

The file’s steps show up in the output as flat:, order kept:, empty levels vanish:.

flatten is what another module would consume; nothing else here is load-bearing for callers.

Key statements

except StopIteration:
    stack.pop()
    continue

Interactive Tools for This Topic

FAQ

Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `flatten` at load time.