Compare Adjacent Values and Running Totals
Core idea
pairwise(iterable) (Python 3.10+) yields overlapping pairs of neighboring values. accumulate(iterable, function, initial=...) yields intermediate totals using addition by default or a two-argument function. A non-None initial value is yielded first. Together they can express changes and balances.
from itertools import pairwiselevels = [12, 15, 11, 11]print([b - a for a, b in pairwise(levels)])Four readings give three overlapping pairs and three differences.
Track a starting balance
from itertools import accumulateprint(list(accumulate([3, -2, 6], initial=10)))Each delta updates the previous balance. The starting balance appears first.
Handle short streams
from itertools import pairwise, accumulateprint(list(pairwise([9])))print(list(accumulate([], initial=5)))print(list(accumulate([8, 3, 7], max)))One item cannot form a pair. An initial value alone is yielded even for empty input. max tracks the running maximum.
Common mistake
pairwise does not divide the input into disjoint pairs; use batched for that. accumulate gives every intermediate result rather than just the final total.
Practice
Compute adjacent changes for [5, 2, 8], then use accumulate with initial=5 to reconstruct the readings.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Adjacent and cumulative values
Check your understanding of pairwise and accumulate.
What is printed?
from itertools import pairwiseprint(list(pairwise([4, 1, 3])))What is printed?
from itertools import accumulateprint(list(accumulate([3, -1], initial=2)))What is printed?
from itertools import accumulateprint(list(accumulate([5, 2, 4], min)))Which tool is appropriate for non-overlapping pairs?