Codectionary / Developer documentation / Python

Iterator Pipelines with itertools

itertools combines small lazy iterators to flatten and limit streams. Work happens as the result is consumed, avoiding a full intermediate list. Run as a Python 3.11+ script.

Syntax

chain.from_iterable(groups); islice(iterator, stop)

Examples

Iterator Pipelines with itertools

Run as a Python 3.11+ script.

from itertools import chain, islice
pages = [["A", "B"], [], ["C", "D"]]
items = chain.from_iterable(pages)
print(list(islice(items, 3)))
print(list(items))
  1. Expected output: ['A', 'B', 'C'] ['D']
  2. islice consumes the first three flattened items. The same iterator then resumes at D; it does not restart.

Best practices

  • Treat iterators as consumable state.
  • Limit infinite iterators before converting them to lists.

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading