Accumulate function in python

Brian Victor homeusenet4 at brianhv.org
Mon Jul 19 12:12:04 EDT 2010


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 ]
>   What is the best way (or pythonic way) to get this.

Now that Steven's given you the simple, pythonic way, I'll just mention
the advanced, complicated and obscure way that might be vaguely familiar
if you're coming from a functional programming background:

x = [ 0, 1, 2, 1, 1, 0, 0, 2, 3 ]
def running_sum(result, current_value):
    return result + [result[-1]+current_value if result else current_value]

reduce(running_sum, x, [])

Having offered this, I don't recall ever seeing reduce used in real
python code, and explicit iteration is almost always preferred.

-- 
Brian




More information about the Python-list mailing list