Group adjacent items that share a key.
What You Will Learn
groupby() groups consecutive runs rather than all equal values across an unordered iterable. Sort by the same key first when you need global grouping, and consume each group before advancing the outer iterator.
Many iterator tools are lazy. Creating the iterator does not necessarily perform the work; advancing it can consume the original source.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from itertools import groupby
records = [("A", 2), ("A", 3), ("B", 1)]
for category, group in groupby(records, key=lambda item: item[0]):
print(category, [item[1] for item in group])
How the Example Works
- The imports provide the standard-library tools used in the demonstration: itertools.
- The variable records holds the result of [('A', 2), ('A', 3), ('B', 1)]. Later lines use that value or inspect how it changes.
- The loop demonstrates when each value is processed or when cleanup and exception handling take effect.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
Expected output from the example:
A [2, 3]
B [1]
Another Example: Compare the Results
Try a second input and compare it with the first. Notice whether the result changes in type, value, order, or number of items.
from itertools import groupby
print([(key, list(group)) for key, group in groupby("AABBA")])
Expected output:
[('A', ['A', 'A']), ('B', ['B', 'B']), ('A', ['A'])]
When You Would Use This
This pattern is useful in readers for CSV files, event streams, or paginated API results, where collecting everything in memory is unnecessary. Because iterator state advances when values are consumed, decide whether you need a reusable collection or a one-time pass. Keep files and connections open until their lazy consumers finish.
Practice: Modify the Code
Summarize sorted sales transactions grouped by department.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Expecting scattered equal keys to merge into one group without sorting first.
- Consuming a one-pass iterator during an earlier check and assuming the same values remain available.
Key Takeaways
- Group adjacent items that share a key.
- groupby() groups consecutive runs rather than all equal values across an unordered iterable.
- Apply this operation only after checking the assumptions and input conditions shown in the example.