Produce a cumulative-sum list where each element is the sum of all values up to that point. The replay shows running advancing with every element and cumulative growing by one entry per step.

By hand

The Pythonic way

itertools.accumulate(values) is a lazy iterator that yields exactly these prefix sums; wrapping with list() materialises them all at once.

naive.py
values = [2, 5, 3, 8, 1, 6, 4]
running = 0
cumulative = []
for v in values:
    running = running + v
    cumulative.append(running)
print('RESULT:', cumulative)
library.py
import itertools
values = [2, 5, 3, 8, 1, 6, 4]
cumulative = list(itertools.accumulate(values))
print('RESULT:', cumulative)
RESULT: [2, 7, 10, 18, 19, 25, 29]

Implementation notes

  • running and cumulative both update every iteration, so no events are zero-delta except the loop-exhaustion step.
  • itertools.accumulate accepts an optional func argument (default: operator.add); passing operator.mul gives a running product instead.
  • The final value of cumulative[-1] equals sum(values) — a useful sanity check.