strboul blog

Flatten multi-dimensional list in Python


This is a snippet I always have it under my toolbelt in Python projects.

def flatten(items):
    for item in items:
        if isinstance(item, (list, tuple)):
            yield from flatten(item)
        else:
            yield item
list(flatten(["a", "b", ("x", "y",), ("h", ["j", "k"],)]))
# >>> ['a', 'b', 'x', 'y', 'h', 'j', 'k']