Accumulate function in python

Vlastimil Brom vlastimil.brom at gmail.com
Mon Jul 19 07:40:29 EDT 2010


2010/7/19 dhruvbird <dhruvbird at gmail.com>:
> 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.
>
> Regards,
> -Dhruv.
> --

Hi,
just a straightworward, naive approach...:

lst_int =  [ 0, 1, 2, 1, 1, 0, 0, 2, 3 ]
acc_int = 0
output_lst = []
for i in lst_int:
    acc_int += i
    output_lst.append(acc_int)
print output_lst

vbr



More information about the Python-list mailing list