Library contents

Python itertools.groupby

itertools.groupby groups adjacent items with the same key and yields a shared-input iterator for each run.

A simple example

itertools.groupby

  1. Start with A, A, B, A
  2. Do this Group consecutive equal entries
  3. Result AA, B, A
The last A begins a new group because B interrupted the run.

Syntax

Python syntax
for key, run in groupby(events)
Run this example in Python

Save the program as lesson.py. Use Python 3.9 or later.

python3 lesson.py

Count consecutive runs of the same status

An operations report receives repeated statuses or events. Decide whether it needs totals, consecutive runs or a snapshot before grouping so the summary preserves the distinctions the operator needs.

From the programevents = ["ready", "ready", "busy", "ready"]
First output lineready 2
lesson.py
from itertools import groupby

events = ["ready", "ready", "busy", "ready"]
for status, run in groupby(events):
    print(status, sum(1 for _ in run))
Output
ready 2
busy 1
ready 1

The same status can appear in several groups when another status comes between occurrences. Consume each run before moving to the next one.

Python documentation for itertools.groupby

Advertisements

Group consecutive bus zones

Stops are recorded in travel order and a zone can appear again later. Group adjacent equal codes as one run. How many runs appear in the sequence?

GivenA · A · B · A
Worked result3

Group kiln readings by status

The studio receives three consecutive ready signals. Group adjacent equal codes as one run. How many runs appear in the sequence?

GivenR · R · R
Worked result1