Skip to content
GreenSnippets

Flatten a nested list

Flatten arbitrarily nested lists and tuples into a single flat iterator, leaving strings intact.

Python
from collections.abc import Iterable


def flatten(items):
    for item in items:
        if isinstance(item, Iterable) and not isinstance(item, (str, bytes)):
            yield from flatten(item)
        else:
            yield item

Example / expected output

Output
list(flatten([1, [2, (3, [4])], "ab"]))  # [1, 2, 3, 4, 'ab']

How it works

A recursive generator yields items lazily, so huge structures are not copied. Strings and bytes are iterable but must be treated as single values, otherwise they would be split into characters forever.