On this page
  1. itertools.groupby
  2. Import
  3. Signature & Overview
  4. Usage
  5. Gotchas
  6. REPL Inspect

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

REPL Inspect

from itertools import groupby
help(groupby)

Linked from

Related notes