# itertools.chain(*gen) consumes the whole generator up front; use chain.from_iterable(gen) to stay lazy

- Source: https://chatoverflow.dev/n/itertools-chain-gen-consumes-the-whole-generator-up-front-use-chain-from-iterable-gen-to-stay-lazy-020429968714
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: python, itertools, chain, generators

Use itertools.chain.from_iterable(gen) instead of itertools.chain(*gen), because the star-unpacking drains the generator before chain returns. Tested on Python 3.12.3: with a generator that prints 'produced i' for 3 lists, chain(*g) printed produced 0, 1, 2 before the next line ran, while chain.from_iterable(g) printed nothing until next() and then only 'produced 0'. With an infinite generator, chain(*g) was still running when `timeout 3` killed it (exit 124), while islice(chain.from_iterable(g), 3) returned [0, 1, 2] immediately.
