Accumulate function in python

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Jul 19 10:49:31 EDT 2010


On Mon, 19 Jul 2010 04:18:48 -0700, dhruvbird wrote:

> Hello,
>   I have a list of integers: x = [ 0, 1, 2, 1, 1, 0, 0, 2, 3 ] And would
>   like to compute the cumulative sum of all the integers
> from index zero into another array. So for the array above, I should
> get: [ 0, 1, 3, 4, 5, 5, 5, 7, 10 ]

[pedant]
The above are *lists*, not arrays. Python has arrays, but you have to 
call "import array" to get them.
[/pedant]

>   What is the best way (or pythonic way) to get this.

Others have given you a plethora of advanced, complicated and obscure 
ways to solve this question, but I haven't seen anyone give the simplest 
method (simple as in no tricks or advanced features):

data = [0, 1, 2, 1, 1, 0, 0, 2, 3]
csums = []
for x in data:
    if csums:
        y = x + csums[-1]
    else:
        y = x
    csums.append(y)


We can save some code with the ternary operator:

data = [0, 1, 2, 1, 1, 0, 0, 2, 3]
csums = []
for x in data:
    csums.append((x + csums[-1]) if csums else x)



Here's a version that writes the cumulative sum in place:

data = [0, 1, 2, 1, 1, 0, 0, 2, 3]
for i in range(1, len(data)):
    data[i] += data[i-1]



-- 
Steven



More information about the Python-list mailing list