Python

flatten — Recursively Flatten Nested Lists

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Yield every leaf from arbitrarily-nested lists/tuples. Strings are intentionally treated as atomic (we don't want to "flatten" "hi" into ["h", "i"]).
Python
Raw
from typing import Iterable, Iterator, Any

def flatten(items: Iterable[Any]) -> Iterator[Any]:
    for item in items:
        if isinstance(item, (list, tuple)) and not isinstance(item, (str, bytes)):
            yield from flatten(item)
        else:
            yield item

list(flatten([1, [2, [3, 4]], 5]))             # [1, 2, 3, 4, 5]
list(flatten(["a", ["b", ["c"]]]))             # ['a', 'b', 'c']  (strings stay whole)
list(flatten([[1, 2], (3, [4, 5])]))           # [1, 2, 3, 4, 5]
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.