Python pairwise: calculate gaps between consecutive readings
For readings from one ordered stream, adjacent gaps need overlapping pairs: the second reading ends one pair and starts the next. itertools.pairwise handles that overlap without slicing the input.
Set up
Tested on Linux with CPython 3.12.14. Use Python 3.12 or later, Bash, a text editor, mktemp, rm and rmdir. The example needs no network access. Run the steps in the same terminal and stop if setup fails. Run Python without -O so the assertions stay enabled.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save this as consecutive_gaps.py:
from itertools import pairwise
readings = iter([10, 14, 14, 9])
pairs = list(pairwise(readings))
gaps = [right - left for left, right in pairs]
print("pairs:", pairs)
print("gaps:", gaps)
print("input after consumption:", list(readings))
print("empty:", list(pairwise([])))
print("singleton:", list(pairwise([10])))
assert gaps == [4, 0, -5]
assert len(pairs) == 3Run:
python3 -B consecutive_gaps.pyObserved output:
pairs: [(10, 14), (14, 14), (14, 9)]
gaps: [4, 0, -5]
input after consumption: []
empty: []
singleton: []Preserve the order that gives the gaps meaning
The pairwise documentation describes successive overlapping pairs. A finite input with at least one item produces one fewer pair than items. Empty and singleton inputs produce no pairs.
The negative gap records the drop from 14 to 9. Sorting first would change the question from consecutive readings to consecutive sorted values. If readings must arrive in increasing time order, validate that requirement separately rather than silently sorting away an ordering problem.
Limits
pairwise consumes its input lazily. This example materializes the pairs to print them, which uses memory proportional to the input. For a large finite stream, calculate each gap in a loop instead. Iterating an unbounded stream to build a list never finishes; the input iterator is also consumed and cannot be replayed without another source.
Clean up
Remove the example file and the temporary directory:
rm -- consecutive_gaps.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.