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.
Code
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: TrueExecution 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
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.