accumulate Builds Running Reductions

itertools.accumulate streams running totals, products, and maxima in one lazy pass, with an optional initial seed and any two-argument function.

PythonData Integrity

Code

pythonsnippet
17 lines
from itertools import accumulate, islice
from operator import mul

daily = [120, 340, 0, 90, 210]
print("running total:", list(accumulate(daily)))

# zip lines up the daily contribution with the running total to show how each step enters the sum
print("paired:", list(zip(daily, accumulate(daily))))

# any binary function: a running product multiplies item by item
print("running product:", list(accumulate([2, 3, 4], mul)))

# rolling maximum: initial provides the starting point for comparisons
print("running max:", list(accumulate([3, 1, 4, 1, 5], max, initial=0)))

# lazy evaluation: accumulate returns an iterator, and islice takes only the prefix you need
print("first three:", list(islice(accumulate(daily), 3)))

A closer look

From operator it pulls accumulate, islice, mul — the imports name exactly which library surface the snippet touches.

The file’s state is a handful of top-level bindings: daily.

What to watch for

  • operator must be installed first — the snippet imports it directly.

Putting it to use

The demo output is labeled (running total:, paired:, running product:), so every printed line maps back to its originating operation.

Interactive Tools for This Topic

FAQ

Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. Every import resolves inside the standard library — `itertools`, `operator`. Its state lives in module-level bindings: `daily`.