itertools Highlights
PY · Comprehensions & Generatorssyntax
import itertoolsexample
from itertools import chain, islice, groupby, product
# Chain multiple iterables
all_items = list(chain([1, 2], [3, 4], [5]))
print(all_items)
# Take first N from any iterable
first_three = list(islice(range(1000000), 3))
print(first_three)
# Cartesian product
sizes = ["S", "M"]
colors = ["red", "blue"]
combos = list(product(sizes, colors))
print(combos)output
[1, 2, 3, 4, 5]
[1, 2, 3]
[('S', 'red'), ('S', 'blue'), ('M', 'red'), ('M', 'blue')]Note itertools functions return lazy iterators. They compose well and avoid creating intermediate lists. See also: accumulate, starmap, tee, zip_longest.