brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's itertools.accumulate gives a running total of a list

Python
~/tips/tip-python-itertools-accumulate-running-total

from itertools import accumulate

accumulate yields the running sum, or a running max or product if you pass a function.

Running totals, like a balance after each transaction, are usually written as a loop with a variable on the side. itertools.accumulate does it in one call.

from itertools import accumulate
import operator

print(list(accumulate([5, -2, 10, 3])))
print(list(accumulate([5, -2, 10, 3], max)))
print(list(accumulate([1, 2, 3, 4], operator.mul)))
print(list(accumulate([100, -30, -20], initial=0)))

The four lines printed:

[5, 3, 13, 16]
[5, 5, 10, 10]
[1, 2, 6, 24]
[0, 100, 70, 50]

The second argument is any function of two values: max gives a running maximum, operator.mul a running product. With initial= (Python 3.8 or newer) the start value is emitted first.

The caveat is the length. Without initial the first item comes out unchanged and the output is as long as the input. With initial it is one longer, so do not zip it against the original list without checking. The result is also an iterator, so wrap it in list() if you need it twice.

You can also pass your own function. This one adds ten times each new value to the running result, starting from 100:

print(list(accumulate([1, 2, 3], lambda t, x: t + x * 10, initial=100)))
[100, 110, 130, 160]

On strings, the default operation is +, so accumulate("abc") gives 'a', 'ab', 'abc'. Floating point rounding shows up as usual: a running product with t * 1.1 yields 110.00000000000001.

Further reading: itertools.accumulate

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link