Python Running Sum in List [duplicate] Python Running Sum in List [duplicate] numpy numpy

Python Running Sum in List [duplicate]


Python 3 has itertools.accumulate for exactly this purpose:

>>> from itertools import accumulate>>> a=[1,2,3]>>> list(accumulate(a))[1, 3, 6]


If you'd like a numpy solution

from numpy import cumsumresult = list(cumsum(a))


How about an ordinary loop?

a = [1,2,3]result = []s = 0for item in a:    s += item    result.append(s)print(result)