Batu Lab NotesPractical developer guides

Generate pairwise changes from a sequence

By Batu ยท English technical notes

Also published in our Blogger archive.

Generate pairwise changes from a sequence

itertools.pairwise turns adjacent values into overlapping two-item tuples. That makes it a direct fit for deriving changes: each (before, after) pair has exactly the two values needed to calculate a difference. temperature_changes subtracts the first value from the second and returns tuples containing both endpoints and the computed delta.

For the input readings, pairwise produces (18, 21), (21, 19), and (19, 24). The result preserves that order, so the output can be read as three consecutive transitions. The assertion verifies the values calculated by this example, including the negative change from 21 to 19.

pairwise consumes its input as an iterator, so it also works with a generator without first building a list. It has no pair to emit for an empty or one-item input, and this function consequently returns an empty list in either case. It compares only neighboring values; it cannot reveal a change from the first value to a later non-adjacent value. If values are not subtractable, such as mixed strings and integers, subtraction raises TypeError.

AI assistance was used to draft this article.

from itertools import pairwise


def temperature_changes(readings):
    return [(before, after, after - before) for before, after in pairwise(readings)]


readings = [18, 21, 19, 24]
changes = temperature_changes(readings)

assert changes == [(18, 21, 3), (21, 19, -2), (19, 24, 5)]
print("changes:", changes)

Expected stdout:

changes: [(18, 21, 3), (21, 19, -2), (19, 24, 5)]

Source: Python documentation: itertools.pairwise