SyntaxStudy
Sign Up
Python Intermediate 4 min read

itertools.groupby

itertools.groupby

itertools.groupby() groups consecutive elements that share a key. Data must be sorted by the key first.

Example
from itertools import groupby

data = [("A", 1), ("A", 2), ("B", 3), ("B", 4)]
for key, group in groupby(data, key=lambda x: x[0]):
    print(key, list(group))
Pro Tip

Sort by the same key before groupby — it only groups consecutive runs.