Python Snippet

Flatten with itertools.chain

Difficulty: Easy

`itertools.chain` lazily concatenates several iterables into a single one without copying their elements, which is the right tool for flattening a list of lists by exactly one level. It works on any iterable (lists, tuples, generators, file objects), so it composes cleanly with the rest of the iterator toolbox. This entry covers `chain`, the unpacking-friendly `chain.from_iterable`, and how it differs from a recursive deep flatten.

Code Snippets
/

Flatten with itertools.chain

Flatten with itertools.chain

`itertools.chain` lazily concatenates several iterables into a single one without copying their elements, which is the right tool for flattening a list of lists by exactly one level. It works on any iterable (lists, tuples, generators, file objects), so it composes cleanly with the rest of the iterator toolbox. This entry covers `chain`, the unpacking-friendly `chain.from_iterable`, and how it differs from a recursive deep flatten.

Python
Easy
3 snippets
py-itertools
py-generators
iterators
py-standard-library

958 views

15

chain(*iterables) walks the first iterable to exhaustion, then the next, and so on, yielding each element exactly once. It accepts any iterable, so you can mix lists, tuples, ranges, and strings without converting them first. Because the result is a lazy iterator, calling next() advances it and a list(...) cast materializes whatever is left. Use chain whenever you find yourself writing a + b + c and one of the operands is not a list, since chain skips the intermediate copies.