Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

itertools.groupby

Groups consecutive items that share a key and yields a key plus a group iterator.

Version: Python 3.14; repository image, production runtime not attested

Syntax

itertools.groupby(iterable, key=None)

Groups consecutive items that share a key and yields a key plus a group iterator.

Repeated keys separated by another key form distinct groups. Consume each group before advancing the outer iterator.

Each run of equal adjacent keys produces a key and an iterator sharing the underlying source. The sequence aabba has runs aa, bb and a. Sorting first joins the a runs, giving three a items then two b items. Materialize each group with list(group) before advancing the outer iterator if its contents are needed later. Saving the iterator object alone cannot preserve its elements.

import itertools as I
groups = I.groupby("aabba")
assert [(k, "".join(g)) for k,g in groups] == [("a","aa"), ("b","bb"), ("a","a")]

Examples

import itertools as I
print([(k, list(g)) for k, g in I.groupby("aabba")])
print([(k, len(list(g))) for k, g in I.groupby(sorted("aabba"))])

Result

[('a', ['a', 'a']), ('b', ['b', 'b']), ('a', ['a'])]
[('a', 3), ('b', 2)]

Each run of equal adjacent keys produces a key and an iterator sharing the underlying source. The sequence aabba has runs aa, bb and a. Sorting first joins the a runs, giving three a items then two b items. Materialize each group with list(group) before advancing the outer iterator if its contents are needed later. Saving the iterator object alone cannot preserve its elements.

Sources