Python Running Sum in List

Dance Party picture Dance Party · Dec 30, 2016 · Viewed 11.3k times · Source

Given the following list:

a=[1,2,3]

I'd like to generate a new list where each number is the sum of it and the values before it, like this:

result = [1,3,6]

Logic:

1 has no preceding value, so it stays the same.

3 is from the first value (1) added to the value of the second number in the list (2)

6 is from the sum of 1 and 2 from the first two elements, plus the third value of 3.

Thanks in advance!

Answer

niemmi picture niemmi · Dec 30, 2016

Python 3 has itertools.accumulate for exactly this purpose:

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