Python Snippet

Group Consecutive Items with groupby

Difficulty: Easy

`itertools.groupby` collapses runs of equal-keyed items into `(key, group_iterator)` pairs. The catch is that it only groups *consecutive* equal items, so the input must already be sorted by the key if you want full grouping. This snippet covers run-length encoding, the sort-first idiom for dict-like grouping, and the iterator gotcha that bites every newcomer.

Code Snippets
/

Group Consecutive Items with groupby

Group Consecutive Items with groupby

`itertools.groupby` collapses runs of equal-keyed items into `(key, group_iterator)` pairs. The catch is that it only groups *consecutive* equal items, so the input must already be sorted by the key if you want full grouping. This snippet covers run-length encoding, the sort-first idiom for dict-like grouping, and the iterator gotcha that bites every newcomer.

Python
Easy
3 snippets
py-itertools
py-generators
iterators
py-standard-library

768 views

5

groupby(iterable) yields a (key, group_iter) pair every time the key changes between consecutive items. Without a key= argument it groups by element identity, which makes one-line run-length encoding trivial. The 'a' run at the end shows up as a separate group because the second 'a' run is not adjacent to the first. RLE is the canonical example, but the same shape pops up in 'longest streak of green builds', 'plateaus in a stock chart', and any other 'consecutive equal' question.