itertools: chain, accumulate, pairwise, groupby

itertools is a box of lazy building blocks. Four you will reach for often:

  • chain(a, b, ...) loops over several iterables as if they were one. chain.from_iterable(lists) flattens one level.
  • accumulate(xs) yields running totals: prefix sums in one line, a common first step in array problems. Pass a function for running max and friends.
  • pairwise(xs) yields neighbouring pairs (a, b), (b, c), .... Good for differences between consecutive items.
  • groupby(xs, key) yields (key, group) for each run of items with the same key.

The groupby gotcha: it groups only consecutive equal keys. It does not collect all matching items like SQL GROUP BY. If the input isn't sorted by the key, the same key shows up in several groups. Sort first, by the same key. Also, each group is an iterator, so use it before moving to the next group.

Run it, then remove the sorted call and see groupby split the groups.