Python › Iterators & the Iterator Protocol

How does itertools.groupby depend on input order, and what's a common mistake when using it?

Advanced

Answer

groupby only groups consecutive items that share a key -- it does not sort or globally group like a SQL GROUP BY. A common mistake is calling groupby on unsorted data, which silently produces multiple separate groups for the same key value scattered through the output instead of one combined group.
import itertools

data = [('a',1), ('b',2), ('a',3)]  # not sorted by key
for k, g in itertools.groupby(data, key=lambda x: x[0]):
    print(k, list(g))
# Output: a [('a',1)]  b [('b',2)]  a [('a',3)]  -- 'a' appears twice!

# Correct: sort first
for k, g in itertools.groupby(sorted(data), key=lambda x: x[0]):
    print(k, list(g))
Real-world example A report generator groups sales records by region using groupby but gets duplicate region sections until the data is sorted by region first.

Common follow-ups: Why doesn't groupby sort automatically?;What's the time complexity difference between groupby+sort and a dict-based grouping?