1

I am stuck with scenario , where i want to add values of list

For example :

my_list=[2,4,5,8]

My Output :

[2,6,11,19] 

It should add like 2 , next value 4+2 : 6 , 6+5 : 11 , 8+11 : 19

How to read previous values ? and add with next value

4 Answers 4

2

This is the exact process that itertools.accumulate() does.

Make an iterator that returns accumulated sums

from itertools import accumulate

my_list = [2,4,5,8]
my_list_accumulated = list(accumulate(my_list))
print(my_list_accumulated)

Output:

[2, 6, 11, 19]
Sign up to request clarification or add additional context in comments.

1 Comment

I love numpy, but this should be the accepted answer ;) +1
1

You can use numpy.cumsum() like below:

a=[2,4,5,8]

np.cumsum(a)
# array([ 2,  6, 11, 19])

np.cumsum(a).tolist()
# [ 2,  6, 11, 19]

Comments

1

You can do something like this:

my_list=[2,4,5,8]
new_list = []
if(len(my_list)>0):
    new_list = my_list[0]
    for i in range(1,len(my_list)):
        new_list.append(my_list[i-1]+my_list[i])

new_list will contain the result

Comments

0

I hope its readable and usefull

my_list = [2, 4, 5, 8]

for index in range(len(my_list)-1):
    if index != 0:
       my_list[index] += my_list[index - 1]


[2, 6, 11, 19]

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.