Count Consecutive Events with Python itertools.groupby

A job log records two retry events, one success, and another retry. A total of three retries hides the fact that the retries happened in two separate runs. For a timeline, the useful summary is two retries, one success, then one retry.

Python’s itertools.groupby() can produce that summary as it reads events in order. This example counts each run in one pass and yields the count as soon as the run ends.

Group Adjacent Events by Status

Run this example:

1
2
3
4
5
6
7
8
from itertools import groupby

statuses = ["retry", "retry", "ok", "retry"]
for status, group in groupby(statuses):
    print(status, sum(1 for _ in group))
# retry 2
# ok 1
# retry 1

Each change in status starts a new group. The final retry follows an ok, so it starts its own group even though an earlier run had the same key. With no key function, groupby() compares the items themselves. Python itertools documentation

Count Runs from Event Records

An event might contain a timestamp and a status. Use the status as the grouping key and pass in records in the order you want to summarize. Save this as event_runs.py:

1
2
3
4
5
6
7
from itertools import groupby
from operator import itemgetter


def count_status_runs(events):
    for status, group in groupby(events, key=itemgetter("status")):
        yield status, sum(1 for _ in group)

The function expects records with a status field. itemgetter("status") reads that field even when the surrounding record contains other data. The caller supplies events in timeline order, and consecutive equal status values form a run.

The count loop uses a running total instead of building a list of records. It can consume a one-shot iterator, such as a generator that decodes one log record at a time. The first record of the next run may already have been read when the current count is yielded because that record marks the boundary. The final run is counted when the input ends.

Consume Each Group Before Advancing

A group is an iterator that reads from the same source as the outer groupby() iterator. Advancing the outer iterator past a group discards any unread members of that group:

1
2
3
4
5
6
7
8
from itertools import groupby

runs = groupby(["retry", "retry", "ok"])
status, retry_group = next(runs)
print(status, next(retry_group))  # retry retry
status, ok_group = next(runs)
print(list(retry_group))          # []
print(status, list(ok_group))     # ok ['ok']

The second outer next() skips the remaining retry to reach the first ok. Saving the group iterator in a list or returning it for later use still leaves it tied to the shared source. The counting function consumes it immediately and returns a durable pair of values. If you need the original records later, use list(group) inside the loop while the group is active. That retains every record in that run and uses memory proportional to its size.

Keep the Output in Timeline Order

Leave the stream in timeline order when the gaps between runs matter. Sorting by status would put the two retry runs together and erase the position of the success between them. Also keep the results as a sequence of pairs. Converting the example output to a dictionary would keep only the last count for retry.

If your report needs a single total per status, use a counter keyed by status. That answers how many times each status occurred across the whole input. The run summary answers how many times each status occurred before it changed.

Test Empty, Uniform, and Repeated Runs

Save this as test_event_runs.py beside event_runs.py and run python test_event_runs.py with Python 3:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from event_runs import count_status_runs


def summarize(statuses):
    events = (
        {"sequence": index, "status": status}
        for index, status in enumerate(statuses)
    )
    return list(count_status_runs(events))


assert summarize([]) == []
assert summarize(["ok"]) == [("ok", 1)]
assert summarize(["retry", "retry"]) == [("retry", 2)]
assert summarize(["retry", "retry", "ok", "retry"]) == [
    ("retry", 2), ("ok", 1), ("retry", 1)
]
assert summarize(["ok", "retry", "ok", "retry"]) == [
    ("ok", 1), ("retry", 1), ("ok", 1), ("retry", 1)
]
print("Status run checks passed.")

Each test supplies a generator whose sequence number changes on every record. The uniform case checks that different records still belong to the same run when their status matches. The alternating case checks that every change opens a new run, including a return to a status already seen.