Python 3.2+Iterators & generatorsterm
itertools.accumulate
itertools
The running intermediate results of applying a function. Sums by default.
Syntax
from itertools import accumulate
accumulate(iterable, func=operator.add)
The difference from functools.reduce: reduce collapses everything into a single value, while accumulate hands you the whole running history — the output has as many items as the input. It returns a lazy iterator, not a list, so printing it directly is useless; wrap it in list() or loop over it, and remember you only get one pass. The function must take two arguments, and the initial parameter (Python 3.8+) seeds the accumulation and makes the output one item longer.
Examples
from itertools import accumulate
print(list(accumulate([1,2,3,4,5]))) # → [1,3,6,10,15] (накопленные суммы)
from itertools import accumulate
import operator
print(list(accumulate([1,2,3,4,5], operator.mul))) # → [1,2,6,24,120] (факториалы)
from itertools import accumulate
# running max
print(list(accumulate([3,1,4,1,5,9,2,6], max))) # → [3,3,4,4,5,9,9,9]
from itertools import accumulate
# С начальным значением (Python 3.8+)
print(list(accumulate([1,2,3], initial=100))) # → [100,101,103,106]
from itertools import accumulate
# Применение в финансах (баланс счёта)
transactions = [1000, -200, -50, 300, -100]
balances = list(accumulate(transactions))
print(balances) # → [1000,800,750,1050,950]
See also
Open in the full glossarydocs.python.orgReport an inaccuracy