Browse topics

itertools building blocks

Version
3.14
Review
Draft

Summary#

The itertools functions combine and slice iterators lazily. They batch items, chain inputs, pair neighbors, take a limited range and group consecutive items that share a key.

Syntax#

python
batched(iterable, size)
chain(first, second)
pairwise(iterable)
islice(iterable, stop)
groupby(iterable, key=function)

Example#

python
from itertools import batched, chain, count, groupby, islice, pairwise
from operator import itemgetter

print(list(batched("ABCDE", 2)))
print(list(chain([1, 2], [3])))
print(list(pairwise([1, 4, 9])))
print(list(islice(count(10, 5), 3)))

events = [("api", 1), ("db", 2), ("api", 3)]
service = itemgetter(0)
print([name for name, _ in groupby(events, service)])
for name, group in groupby(sorted(events, key=service), service):
    print(name, [number for _, number in group])

Expected output#

Text
[('A', 'B'), ('C', 'D'), ('E',)]
[1, 2, 3]
[(1, 4), (4, 9)]
[10, 15, 20]
['api', 'db', 'api']
api [1, 3]
db [2]

Common mistakes#

groupby starts a new group whenever the key changes, so sort by the same key first when all equal keys belong together. Each group shares the source iterator. Convert a group to a list before advancing if you need it later. batched can return a shorter final batch. Use strict=True to reject it on Python 3.13 or later.

Version applicability#

chain, islice and groupby work on all Python 3 releases. The step argument of count was added in Python 3.1. pairwise requires 3.10, batched requires 3.12, and its strict option requires 3.13. The complete example starts at 3.12.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0