Python itertools.groupby
last modified November 29, 2026 Python 3.15
In this article we show how to group items with the groupby
function from the itertools module.
The groupby function takes an iterable and an optional key
function. It goes through the items in order and collects runs of
consecutive items that have the same key. For each run, it produces a pair:
the key and an iterator over the items of the run. The function does not
look ahead or back, so equal keys that are not next to each other end up in
separate groups. To group all items with the same key, the data must first
be sorted by that key.
Because it works on consecutive items, groupby is useful for two
tasks: grouping sorted data, such as records sorted by a field, and finding
runs in a sequence, such as repeated characters or a streak of days.
The first groups
Without a key function, groupby compares the items
themselves. A string is an iterable of characters.
from itertools import groupby
text = "aaabccdddd"
for key, group in groupby(text):
print(key, list(group))
Each run of equal characters becomes one group. The group is an iterator, so we turn it into a list to print its items.
$ python first_groups.py a ['a', 'a', 'a'] b ['b'] c ['c', 'c'] d ['d', 'd', 'd', 'd']
Run-length encoding
Run-length encoding is a simple compression method. It stores a run of
equal values as a count followed by the value. This is exactly what
groupby finds.
from itertools import groupby
signal = "WWWWBBWWWWWWBWW"
encoded = ""
for key, group in groupby(signal):
encoded += f"{len(list(group))}{key}"
print(encoded)
For each group, len(list(group)) counts the characters in the
run. The fifteen characters of the signal shrink to ten.
$ python run_length.py 4W2B6W1B2W
Sorting before grouping
The groupby function starts a new group every time the key
changes. Unsorted data therefore produces several groups with the same
key.
from itertools import groupby
colours = ["red", "red", "blue", "red", "blue", "blue"]
print("as given:")
for key, group in groupby(colours):
print(" ", key, len(list(group)))
print("sorted:")
for key, group in groupby(sorted(colours)):
print(" ", key, len(list(group)))
In the original order, the colours alternate and groupby
returns four groups, two for each colour. After sorting, equal colours are
next to each other and each colour forms exactly one group. The
Python sort list article covers sorting in
detail.
$ python unsorted.py as given: red 2 blue 1 red 1 blue 2 sorted: blue 3 red 3
The key function
The key parameter takes a function that computes the key for
each item. The data must be sorted with the same function, so that items
with equal keys are adjacent.
from itertools import groupby
words = ["sky", "tree", "ox", "cloud", "rain", "sun", "storm", "go"]
by_length = sorted(words, key=len)
for length, group in groupby(by_length, key=len):
print(length, list(group))
The built-in len function serves as the key, so the words are
grouped by their length. Sorting is stable: words of the same length keep
their original order, so ox comes before go.
$ python key_function.py 2 ['ox', 'go'] 3 ['sky', 'sun'] 4 ['tree', 'rain'] 5 ['cloud', 'storm']
Grouping records
A common use of groupby is grouping records by one of their
fields. Here the records are dictionaries and the key function returns the
city of a sale.
from itertools import groupby
sales = [
{"city": "Brno", "product": "tea", "amount": 120},
{"city": "Kosice", "product": "coffee", "amount": 340},
{"city": "Brno", "product": "coffee", "amount": 210},
{"city": "Zilina", "product": "tea", "amount": 90},
{"city": "Kosice", "product": "tea", "amount": 150},
{"city": "Brno", "product": "cocoa", "amount": 60},
]
def by_city(sale):
return sale["city"]
for city, group in groupby(sorted(sales, key=by_city), key=by_city):
print(city)
for sale in group:
print(f" {sale['product']:8} {sale['amount']:4}")
The same by_city function is passed to sorted and
to groupby. Using one function for both guarantees that the
sort order matches the grouping. Inside a city, the sales keep the order of
the original list.
$ python records.py Brno tea 120 coffee 210 cocoa 60 Kosice coffee 340 tea 150 Zilina tea 90
Aggregating groups
Instead of printing the items of each group, we can reduce them to summary values such as counts, totals, and maximums.
from itertools import groupby
sales = [
{"city": "Brno", "product": "tea", "amount": 120},
{"city": "Kosice", "product": "coffee", "amount": 340},
{"city": "Brno", "product": "coffee", "amount": 210},
{"city": "Zilina", "product": "tea", "amount": 90},
{"city": "Kosice", "product": "tea", "amount": 150},
{"city": "Brno", "product": "cocoa", "amount": 60},
]
def by_product(sale):
return sale["product"]
for product, group in groupby(sorted(sales, key=by_product), key=by_product):
amounts = [sale["amount"] for sale in group]
print(f"{product:8} count={len(amounts)} total={sum(amounts):4} "
f"max={max(amounts)}")
The group iterator can be consumed only once. To compute several values from
one group, we first collect the amounts into a list with a list
comprehension. Then len, sum, and
max work on the list.
$ python totals.py cocoa count=1 total= 60 max=60 coffee count=2 total= 550 max=340 tea count=3 total= 360 max=150
Grouping by several fields
A key function can return a tuple. Tuples compare field by field, so sorting by a tuple orders the records by the first field and then by the second.
from itertools import groupby
sales = [
{"city": "Brno", "product": "tea", "amount": 120},
{"city": "Kosice", "product": "coffee", "amount": 340},
{"city": "Brno", "product": "tea", "amount": 80},
{"city": "Brno", "product": "coffee", "amount": 210},
{"city": "Kosice", "product": "tea", "amount": 150},
{"city": "Kosice", "product": "coffee", "amount": 40},
]
def city_product(sale):
return sale["city"], sale["product"]
for (city, product), group in groupby(sorted(sales, key=city_product),
key=city_product):
total = sum([sale["amount"] for sale in group])
print(f"{city:7} {product:7} {total:4}")
The key is a pair of city and product. The loop unpacks the pair directly in
its target, and each line shows the total for one combination. The two tea
sales in Brno are merged into one group. The
operator module provides
itemgetter, which can build such key functions without a
def.
$ python two_keys.py Brno coffee 210 Brno tea 200 Kosice coffee 380 Kosice tea 150
Groups share the iterator
The groups are not independent copies. They all read from the one underlying
iterator that groupby advances. When groupby moves
on to the next group, the previous group becomes empty.
from itertools import groupby
data = "aabbbc"
groups = {}
for key, group in groupby(data):
groups[key] = group
print({key: list(group) for key, group in groups.items()})
groups = {}
for key, group in groupby(data):
groups[key] = list(group)
print(groups)
The first loop stores the group iterators in a dictionary. By the time we
read them, groupby has moved past their items, and all three are
empty. The second loop turns each group into a list right away, while it is
still the current group. This is the right way to keep groups for later.
$ python shared_iterator.py
{'a': [], 'b': [], 'c': []}
{'a': ['a', 'a'], 'b': ['b', 'b', 'b'], 'c': ['c']}
groupby versus a dictionary
To group data that is not sorted, sorting first costs O(n log n) time. A dictionary of lists groups the data in a single pass and keeps the order in which the keys first appear.
from itertools import groupby
words = ["sky", "tree", "ox", "cloud", "rain", "sun", "storm", "go"]
by_letter = {}
for word in words:
by_letter.setdefault(word[0], []).append(word)
print(by_letter)
with_groupby = {
letter: list(group)
for letter, group in groupby(sorted(words), key=lambda w: w[0])
}
print(with_groupby)
The setdefault method returns the list for a letter, creating
an empty one on the first occurrence. The groupby version needs
sorted input and returns the keys in sorted order. Use a dictionary to group
unsorted data; use groupby when the data is already sorted, when
the order of the runs matters, or when the data is too large to keep in
memory, since groupby holds only the current group. The
collections module offers
defaultdict for the dictionary approach.
$ python dict_grouping.py
{'s': ['sky', 'sun', 'storm'], 't': ['tree'], 'o': ['ox'], 'c': ['cloud'], 'r': ['rain'], 'g': ['go']}
{'c': ['cloud'], 'g': ['go'], 'o': ['ox'], 'r': ['rain'], 's': ['sky', 'storm', 'sun'], 't': ['tree']}
Finding streaks
In data with a natural order, such as days, sorting would destroy the
information. Here groupby finds runs in the original order. We
look for the longest streak of rainy days.
from itertools import groupby
days = [
("Mar 01", 3.1), ("Mar 02", 0.0), ("Mar 03", 1.2), ("Mar 04", 5.4),
("Mar 05", 2.2), ("Mar 06", 0.0), ("Mar 07", 0.0), ("Mar 08", 0.4),
("Mar 09", 0.8), ("Mar 10", 1.5), ("Mar 11", 3.9), ("Mar 12", 0.0),
]
def is_rainy(day):
return day[1] > 0
longest = []
for rainy, group in groupby(days, key=is_rainy):
run = list(group)
if rainy and len(run) > len(longest):
longest = run
print(f"longest rainy streak: {len(longest)} days, "
f"{longest[0][0]} to {longest[-1][0]}")
print("total rain:", round(sum([day[1] for day in longest]), 1), "mm")
The key function returns True for a rainy day and
False for a dry one, so the groups are alternating rainy and dry
periods. Each rainy run is compared with the longest one found so far. The
last two lines print the dates of the streak and its total rainfall.
$ python streaks.py longest rainy streak: 4 days, Mar 08 to Mar 11 total rain: 6.6 mm
Source
itertools.groupby documentation, Sorting techniques
In this article we have grouped data with itertools.groupby. We have found runs of equal items, sorted data before grouping, used key functions and composite keys, aggregated groups, seen that groups share one iterator, and compared groupby with grouping in a dictionary. See also Python itertools, Python sort list, and Python lambda function.
Author
List all Python tutorials.