On this page
itertools.groupby
Prev: itertools.filterfalse | Up: itertools | Next: itertools.islice
Rel: itertools.accumulate, itertools.batched, itertools.chain, itertools.combinations
Ref: docs.python.org — itertools.groupby
Tags: #public #python3 #stdlib #itertools
Import
import itertools
from itertools import groupby
Signature & Overview
itertools.groupby(iterable, key=None)
make an iterator that returns consecutive keys and groups from the iterable iterable Elements to divide into groups according to the key function.
Usage
from itertools import groupby
rows = [("a", 1), ("a", 2), ("b", 3), ("a", 4)]
# Sort by the same key first if you want global grouping instead of consecutive runs
grouped = {k: [v for _, v in g] for k, g in groupby(sorted(rows), key=lambda r: r[0])}
assert grouped == {"a": [1, 2, 4], "b": [3]}
Gotchas
- Only groups consecutive runs: Unlike SQL
GROUP BY, unsorted input splits identical keys into separate groups—sort with the samekey=first unless run-length grouping is intentional. - Exhaust each group before advancing: Each sub-iterator shares the parent stream; materialize it (
list(g)) before moving to the next group.
REPL Inspect
from itertools import groupby
help(groupby)
Linked from
Related notes
- tuts/python3/stdlib_module/itertools/filterfalse Linked here; links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/islice Linked here; links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/itertools/accumulate Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/batched Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/chain Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/combinations Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/combinations_with_replacement shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/compress shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/count shared tags: #itertools, #stdlib