Sub topic 10
Grouping consecutive items with groupby
This chapter assumes you know Python loops, tuples, sorted with key=, and the iterator basics from earlier chapters. itertools.groupby splits an iterable into runs of consecutive items that share a key. It looks like SQL's GROUP BY, but it works differently, and that difference causes most of the bugs people hit with it.
How groupby works
groupby(iterable, key=None) yields pairs of (key, group). The key is the value your key function returned for the run. The group is an iterator over the items in that run. If you omit key, each item is its own key.
A new group starts whenever the key changes from the previous item. Equal keys that are not next to each other produce separate groups.
from itertools import groupby
text = "aaabccdd"
print([(ch, len(list(run))) for ch, run in groupby(text)])This prints [('a', 3), ('b', 1), ('c', 2), ('d', 2)]. It is run-length encoding in one line.
Sort first when grouping by key
Because only neighbours are compared, you must sort by the same key when you want one group per distinct key.
from itertools import groupby
from operator import itemgetter
data = [('fruit', 'apple'), ('veg', 'kale'), ('fruit', 'pear'), ('fruit', 'fig')]
data.sort(key=itemgetter(0))
for kind, items in groupby(data, key=itemgetter(0)):
print(kind, [name for _, name in items])The output is:
fruit ['apple', 'pear', 'fig']
veg ['kale']list.sort is stable, so items inside each key keep their original order. Without the sort, fruit would appear twice, because veg sits between its items.
from itertools import groupby
print([(k, len(list(g))) for k, g in groupby([1, 1, 2, 1])])This prints [(1, 2), (2, 1), (1, 1)]. The key 1 shows up as two separate groups.
Groups are shared iterators
Each group reads from the same underlying iterator as groupby itself. When you advance to the next key, the previous group is invalidated. Two consequences follow:
- Consume a group (or copy it with
list) before you move on to the next pair. - Do not turn the outer
groupbyinto a list and read the groups afterwards.
from itertools import groupby
groups = list(groupby("aabb"))
print(list(groups[0][1]))This prints []. The outer list call advanced past the first group before you read it. The safe pattern copies each group inside the loop or comprehension:
from itertools import groupby
result = {k: list(g) for k, g in groupby("aabb")}
print(result)This prints {'a': ['a', 'a'], 'b': ['b', 'b']}. A dictionary comprehension like this keeps only the last group for a repeated key, so use it only on sorted input.
Common patterns
Grouping by a computed property needs a key function. Sort with the same function:
from itertools import groupby
words = ["bee", "ant", "cat", "dove", "frog", "owl"]
words.sort(key=len)
for length, group in groupby(words, key=len):
print(length, list(group))The output is 3 ['bee', 'ant', 'cat', 'owl'] and then 4 ['dove', 'frog'].
Because groupby is lazy, it also suits sorted or naturally ordered streams that are too large for memory. Log lines ordered by timestamp, or rows from a database query with ORDER BY, can be grouped one run at a time.
When to choose something else
Use a defaultdict(list) when the data is unsorted and fits in memory. It needs one pass and no sort. Use groupby when the input is already ordered, or when runs themselves matter, as in run-length encoding or detecting streaks.
Exercise
Given nums = [1, 1, 2, 2, 2, 1], what does [(k, len(list(g))) for k, g in groupby(nums)] return, and how would you get a single count per distinct number?
Show answer
It returns [(1, 2), (2, 3), (1, 1)] because the final 1 is a separate run. To get one count per distinct number, sort first with sorted(nums), which gives [(1, 3), (2, 3)]. Alternatively, use collections.Counter, which needs no sorting.