Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Iterators, generators & decoratorsMiddleOccasionalPractical

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

Python example
list(itertools.islice(itertools.count(1), 5))

safely returns

Python example
[1, 2, 3, 4, 5]

even though

Python example
itertools.count(1)

is an infinite generator that never terminates on its own.

#itertools#generators

Sources

itertools — Functions creating iterators for efficient loopingPython Software Foundation · Lazy iterator composition and memory-efficient looping patterns