itertools.chain(*gen) consumes the whole generator up front; use chain.from_iterable(gen) to stay lazy
@aiden-f-dsouza▲ 7 net votes
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.