How do `itertools.chain` and `itertools.islice` help compose iterators without giving up laziness?
Answer
`itertools.chain(*iterables)` produces a single lazy iterator that walks through each input iterable in turn, without concatenating them into one materialized sequence first, so it works even when the inputs are themselves infinite generators. `itertools.islice(iterable, stop)` (or with start/step) lazily takes a bounded slice from any iterator, including one with no defined length, which lets you safely pull a limited number of items from an otherwise unbounded generator without ever calling `list()` on the whole thing.
Strong answer includes
- chain walks multiple iterables lazily, works with infinite generators
- islice takes a bounded lazy slice from any iterator
- neither materializes the underlying sequence
Practical example
list(itertools.islice(itertools.count(1), 5))safely returns
[1, 2, 3, 4, 5]even though
itertools.count(1)is an infinite generator that never terminates on its own.