Flatten a nested list
Flatten arbitrarily nested lists and tuples into a single flat iterator, leaving strings intact.
- Python
- GreenSnippets
- MIT
- Executed with Python 3.11
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 itemExample / expected 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.
Related snippets
- Python Tested
Group items by a key
Collect a list of records into a dictionary of lists keyed by a field or function result.
- Python Tested
Remove duplicates but keep order
Deduplicate a list while preserving the first occurrence order, for hashable values or by key.
- Python Tested
Token bucket rate limiter
Allow bursts but cap the sustained request rate with a small thread-safe token bucket.
- Python Tested
Time a block of code with a context manager
Measure elapsed wall-clock time of a with-block using time.perf_counter.

