Python itertools Advanced: groupby, accumulate, and tee
Beyond chain and combinations, itertools has groupby for grouping, accumulate for running totals, and tee for duplicating iterators. I covered chain and combinations in a previous article. Those are the itertools functions I use most, but the module has several others that solve problems requiring more code without them. groupby , accumulate , and tee each address a specific pattern that comes up in data processing. They are less common but worth knowing. groupby for Grouping Consecutive Items The groupby function groups consecutive items that share a key. It returns an iterator of (key, group) pairs, where group is itself an iterator. The critical detail is that it only groups consecutive items. if the data is not sorted by, items with the same key end up in separate groups. from itertools import groupby # Group consecutive identical elements data = [1, 1, 1, 2, 2, 3, 1, 1] for key, group in groupby(data): print(key, list(group)) # 1 [1, 1, 1] # 2 [2, 2] # 3 [3] # 1 [1, 1] To group all items with the same key, sort first. The key function extracts the grouping key…