You want itertools.accumulate()
(added in Python 3.2). Nothing extra needed, already implemented for you.
In earlier versions of Python where this doesn't exist, you can use the pure python implementation given:
def accumulate(iterable, func=operator.add):
'Return running totals'
# accumulate([1,2,3,4,5]) --> 1 3 6 10 15
# accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
it = iter(iterable)
total = next(it)
yield total
for element in it:
total = func(total, element)
yield total
This will work perfectly with any iterable, lazily and efficiently. The itertools
implementation is implemented at a lower level, and therefore even faster.
If you want it as a list, then naturally just use the list()
built-in: list(accumulate(x))
.