Sub topic 10
Grouping consecutive items with groupby
This chapter assumes you know Python functions, loops and comprehensions, tuples and dictionaries, and lambda and the key= argument of sorted. You should also know what an iterator is and that it can be consumed only once. Both ideas matter here, because groupby is lazy and its output depends on how you consume it.
What groupby does
itertools.groupby(iterable, key=None) walks through an iterable and yields one pair for each run of consecutive items that share the same key. Each pair is (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.
The word that matters is consecutive. groupby does not look back or ahead to collect all matching items. It starts a new group each time the key changes. This differs from SQL GROUP BY and from collections.defaultdict(list), which gather every matching item no matter where it appears.
If you leave out key, groupby uses the item itself as the key. That makes it a compact way to find runs of repeated values.
from itertools import groupby
text = "aaabccdd"
for char, run in groupby(text):
print(char, len(list(run)))This prints:
a 3
b 1
c 2
d 2The output is a run-length encoding of the string. Each run is an iterator, so len(run) would raise a TypeError. You have to consume it, here with list(run).
Sorting first when you group by key
Because groupby only merges neighbours, unsorted input produces several groups for the same key. Here is the effect on a small list.
from itertools import groupby
from operator import itemgetter
data = [('fruit', 'apple'), ('veg', 'kale'), ('fruit', 'pear'), ('fruit', 'fig')]
print("Unsorted:")
for kind, items in groupby(data, key=itemgetter(0)):
print(kind, [name for _, name in items])
data.sort(key=itemgetter(0))
print("Sorted:")
for kind, items in groupby(data, key=itemgetter(0)):
print(kind, [name for _, name in items])The unsorted pass prints fruit twice, because the veg item splits the fruit items into two runs:
Unsorted:
fruit ['apple']
veg ['kale']
fruit ['pear', 'fig']
Sorted:
fruit ['apple', 'pear', 'fig']
veg ['kale']Sorting by the same key you group by is the standard fix. Python's sort is stable, so items with equal keys keep their original relative order. That is why apple, pear, fig stay in that order inside the fruit group.
Sorting costs O(n log n) time and needs the whole input in memory, because sorted builds a list. If your data is already ordered, for example rows read from a file sorted by date, you can skip the sort and keep the constant-memory benefit of groupby. Use the sort only when you need it.
The shared iterator: the main gotcha
The groups are not independent lists. groupby reads from a single underlying iterator, and each group is a view onto that same iterator. When you advance to the next key, the previous group is invalidated. The documentation states this directly: the group is shared with the source iterator, so it is not available after groupby moves on.
This code looks harmless and gives wrong results.
from itertools import groupby
words = ["ant", "ape", "bat", "bee", "cat"]
groups = list(groupby(words, key=lambda w: w[0]))
for key, group in groups:
print(key, list(group))It prints:
a []
b []
c []list(groupby(...)) ran the outer iterator to the end before you looked at any group. By then every group had been skipped over, so each one is empty.
There are two safe patterns. The first is to consume each group inside the loop body, before the loop advances.
from itertools import groupby
words = ["ant", "ape", "bat", "bee", "cat"]
for key, group in groupby(words, key=lambda w: w[0]):
print(key, list(group))This prints a ['ant', 'ape'], b ['bat', 'bee'] and c ['cat'].
The second is to copy each group into a container as you go, when you need to keep the results.
from itertools import groupby
words = ["ant", "ape", "bat", "bee", "cat"]
grouped = {key: list(group) for key, group in groupby(words, key=lambda w: w[0])}
print(grouped)The dictionary comprehension consumes each group before moving to the next key, so the result is {'a': ['ant', 'ape'], 'b': ['bat', 'bee'], 'c': ['cat']}. Note that a dictionary keeps only one entry per key. If the input were unsorted, a later run would overwrite an earlier run with the same key, and you would lose data without any error.
If you do not consume a group at all, groupby skips the remaining items in it for you when you ask for the next pair. That is correct behaviour, but it means a group you ignore is gone.
Choosing a key function
The key argument is any callable that takes one item and returns a comparable value. Two items are in the same run when their keys compare equal with ==. Common choices are operator.itemgetter, operator.attrgetter, a lambda, or a built-in such as len.
Grouping words by length after sorting by length:
from itertools import groupby
words = ["to", "be", "or", "not", "to", "be", "that", "is"]
words.sort(key=len)
for length, group in groupby(words, key=len):
print(length, list(group))The output is:
2 ['to', 'be', 'or', 'to', 'be', 'is']
3 ['not']
4 ['that']The key function runs once per item, not once per group. Keep it cheap, and avoid keys with side effects.
The key does not have to be a field. A key can classify items by a rule. This example groups numbers into runs of the same parity.
from itertools import groupby
numbers = [2, 4, 6, 1, 3, 8, 10, 5]
for is_even, run in groupby(numbers, key=lambda n: n % 2 == 0):
print("even" if is_even else "odd", list(run))The output shows each run in order, without sorting, because here the order of the runs is the information we want:
even [2, 4, 6]
odd [1, 3]
even [8, 10]
odd [5]This is a case where unsorted input is the right choice. Sorting would destroy the run structure.
Finding runs of consecutive integers
A well-known recipe uses groupby to split a sorted list of integers into runs where each value is one more than the last. The trick is a key that stays constant inside a run: the difference between the value and its position.
from itertools import groupby
nums = [1, 2, 3, 7, 8, 10, 11, 12]
for _, run in groupby(enumerate(nums), key=lambda pair: pair[1] - pair[0]):
block = [value for _, value in run]
print(block)For 1, 2, 3 the differences are 1-0, 2-1, 3-2, all equal to 1. When 7 appears at index 3, the difference becomes 4, which starts a new group. The output is:
[1, 2, 3]
[7, 8]
[10, 11, 12]The recipe assumes the input is sorted and has no duplicates. A repeated value breaks the constant difference and splits the run.
Using the two-argument form of the key
groupby has no second key for the value. If you want to transform the items while grouping, do it as you consume each group. This example totals sales per region.
from itertools import groupby
from operator import itemgetter
sales = [
("north", 120),
("south", 80),
("north", 45),
("south", 200),
("east", 60),
]
sales.sort(key=itemgetter(0))
for region, rows in groupby(sales, key=itemgetter(0)):
total = sum(amount for _, amount in rows)
print(region, total)The output is:
east 60
north 165
south 280Because sum consumes the group inside the loop, no list is built, and memory stays flat for each group. That is the benefit over collecting everything into a dictionary first.
groupby compared with other tools
| Task | Tool | Needs sorted input | Memory |
|---|---|---|---|
| Group all items by key into a dictionary | `defaultdict(list)` | No | Holds all items |
| Group items of an already ordered stream | `itertools.groupby` | Yes, by the same key | One group at a time |
| Find runs of equal neighbours | `itertools.groupby` | No | One group at a time |
| Group rows in a table | `pandas.DataFrame.groupby` | No | Holds the table |
Choose groupby when the data is already ordered, when you want runs rather than global groups, or when the data is too large to hold in memory. Choose defaultdict(list) when order does not matter and the data fits in memory, because it avoids the sort and has no shared-iterator trap.
Edge cases
- An empty input yields no pairs, so the loop body never runs.
- Keys are compared with
==, so1and1.0count as the same key and share a group. - A key that returns an unhashable value such as a list still works, because
groupbyonly compares keys and does not hash them. groupbydoes not require keys to be orderable, only comparable for equality. Sorting does require ordering, so sorting by a key that mixes types such asintandstrraisesTypeError.- If you keep a reference to the
keyvalue across iterations, that is safe. Only thegroupiterator is invalidated. - Passing a one-shot iterator such as a generator works, but you cannot restart it. Run the grouping once and store what you need.
Exercise
The code below is meant to build a dictionary mapping each first letter to its words, but it prints {'a': [], 'b': [], 'c': []}. Explain why, and rewrite the last two lines so it prints {'a': ['ant', 'ape'], 'b': ['bat'], 'c': ['cat']}.
from itertools import groupby
words = ["ant", "ape", "bat", "cat"]
pairs = list(groupby(words, key=lambda w: w[0]))
print({key: list(group) for key, group in pairs})
Show answer
list(groupby(...)) runs the outer iterator to the end before any group is read. Each group is a view onto the shared source, so every group has already been skipped and is empty by the time list(group) runs. Consume each group while the loop is on it, by building the dictionary directly from groupby: print({key: list(group) for key, group in groupby(words, key=lambda w: w[0])}). The input is already ordered by first letter, so no sort is needed.
Exercise
Given readings = [('a', 3), ('b', 5), ('a', 4), ('a', 1), ('b', 2)], write code that prints the sum of the numbers for each letter, in alphabetical order, using groupby. What must you do before calling groupby, and why?
Show answer
Sort by the letter first, because groupby only merges consecutive items with equal keys: readings.sort(key=itemgetter(0)). Then loop with for letter, rows in groupby(readings, key=itemgetter(0)): print(letter, sum(n for _, n in rows)). The output is a 8, then b 7. Without the sort, the letter a would appear in two separate groups and the totals would be split.