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!
7 Answers
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 cumsum
result = list(cumsum(a))
How about an ordinary loop?
a = [1,2,3]
result = []
s = 0
for item in a:
s += item
result.append(s)
print(result)
Python has a function for this.
import itertools
result = list(itertools.accumlate([1, 2, 3]))
Python itertools solve some problems really well you should take some time and read over them.
try this..
def running_sum(a):
tot = 0
for item in a:
tot += item
yield tot
a = [1,2,3,4]
print list(running_sum(a))
There are about a hundred different ways to do this kind of cumulative sum. Depending on what you actually want to use the result for, a less obvious or less general-purpose solution might be more time- or memory-efficient—although the simple solution below is O(1) in terms of memory and O(N) in time.
The most straightforward procedural approach in virtually every imperative programming language goes something like this:
csum=0
result=[]
for val in a:
csum += val
result.append(csum)
The Python standard library also includes a function to do just this: itertools.accumulate.
import itertools
result = list(itertools.accumulate(a))
Avinash Raj's code doesn't work correctly.
a = [1,2,3]
b = [sum(a[:(i+1)]) for i, j in enumerate(a)]
print(b)
Edited based on @Avinash Raj