CKTIS / Python
itertools.accumulate
Yields successive running totals, or successive results of a supplied binary operation.
Version: Python 3.14; repository image, production runtime not attested
Syntax
itertools.accumulate(iterable, func=None, *, initial=None)Yields successive running totals, or successive results of a supplied binary operation.
Providing an initial value emits it first, including when the input is empty.
With default addition, the first input seeds the running total and each later input updates it: 2, then 7, then 6. A non-None initial value is yielded before the first input. Even an empty input therefore yields 7 when initial=7. A binary function can replace addition.
import itertools as I
from operator import mul
assert list(I.accumulate([2, 3], mul, initial=4)) == [4, 8, 24]
assert list(I.accumulate([], initial=None)) == []
Examples
import itertools as I
print(list(I.accumulate([2, 5, -1])))
print(list(I.accumulate([], initial=7)))
Result
[2, 7, 6] [7]
With default addition, the first input seeds the running total and each later input updates it: 2, then 7, then 6. A non-None initial value is yielded before the first input. Even an empty input therefore yields 7 when initial=7. A binary function can replace addition.