itertools.groupby looks like SQL’s GROUP BY, and that’s exactly why it trips people up. It only groups items that sit next to each other.
from itertools import groupby
data = ["b1", "a1", "b2", "a2"]
first = lambda s: s[0]
print([(k, list(g)) for k, g in groupby(data, key=first)])
# [('b', ['b1']), ('a', ['a1']), ('b', ['b2']), ('a', ['a2'])]
print([(k, list(g)) for k, g in groupby(sorted(data, key=first), key=first)])
# [('a', ['a1', 'a2']), ('b', ['b1', 'b2'])]
The first call gives you four groups, with ‘b’ and ‘a’ each showing up twice. Sort on the same key function first and you get the two groups you expected.
The unsorted behaviour is handy on purpose sometimes. I like it for collapsing runs in a log, like several identical lines in a row, where the order matters and you want each run counted separately.
There’s a second trap: each group is an iterator that shares data with the main one. As soon as groupby moves on to the next key, the previous group is gone. If you need the items later, turn them into a list right away, like the list(g) above does. And if you don’t care about order at all, a defaultdict(list) is often simpler.
Further reading: itertools.groupby