Sub topic 2
Joining Sequences with `itertools`
This chapter assumes you know functions, loops, comprehensions, lambda, key=, and basic iterators. The examples use Python 3.10 or newer. batched requires Python 3.12.
Joining and filtering streams
chain reads several iterables as one sequence. chain.from_iterable does the same when the input is itself an iterable of iterables.
from itertools import (
chain, takewhile, dropwhile, filterfalse, compress
)
print(list(chain([1, 2], [3, 4])))
print(list(chain.from_iterable([[1, 2], [3], [4, 5]])))
values = [1, 4, 6, 2]
print(list(takewhile(lambda x: x < 5, values)))
print(list(dropwhile(lambda x: x < 5, values)))
print(list(filterfalse(lambda x: x < 5, values)))
print(list(compress(["a", "b", "c"], [1, 0, 1])))takewhile stops at the first failure. dropwhile skips matching items only at the beginning. filterfalse keeps items for which the predicate is false. compress keeps data where the corresponding selector is true.
Running results and pairing
accumulate produces intermediate results, such as running totals. starmap calls a function with each tuple unpacked as arguments.
from itertools import accumulate, starmap, zip_longest, pairwise
print(list(accumulate([2, 3, 4])))
print(list(starmap(pow, [(2, 3), (3, 2)])))
print(list(zip_longest("ab", [1, 2, 3], fillvalue="-")))
print(list(pairwise([10, 20, 30])))zip_longest pads shorter inputs. pairwise creates overlapping neighboring pairs.
Batching and grouping
Use batched to split an iterable into tuples of at most the requested size. For older Python versions, use an islice-based recipe. groupby groups consecutive items, not every item with the same key, so sort first when necessary.
from itertools import batched, groupby
from operator import itemgetter
print(list(batched("ABCDEFG", 3)))
data = [("fruit", "apple"), ("veg", "kale"), ("fruit", "pear")]
for kind, items in groupby(sorted(data, key=itemgetter(0)),
key=itemgetter(0)):
print(kind, [name for _, name in items])Exercise
Why should data usually be sorted before grouping it with groupby?
Show answer
groupby joins only consecutive items with equal keys, so sorting places equal-key items next to each other.