Python theorytheory 0/50 · 0%
Collections · medium

37. Iterables, `itertools`, and functional helpers

map, filter, reduce, and itertools building blocks.

`map`/`filter` apply a function across an iterable lazily; `functools.reduce` folds an iterable into a single value.

python
from functools import reduce
from itertools import chain, groupby

doubled = list(map(lambda x: x * 2, [1, 2, 3]))
evens = list(filter(lambda x: x % 2 == 0, range(10)))
total = reduce(lambda acc, x: acc + x, [1, 2, 3], 0)

flat = list(chain([1, 2], [3, 4]))   # [1, 2, 3, 4]

`itertools.groupby` groups consecutive equal keys (input must be pre-sorted by that key to group all occurrences), and `itertools.chain` concatenates iterables without copying them into one list first.

Check your understanding

  1. 1. What does `reduce(lambda acc, x: acc + x, [1,2,3], 0)` compute?

  2. 2. What must be true of input for itertools.groupby to group all matching elements together?

  3. 3. What does `itertools.chain([1,2],[3,4])` produce when iterated?