user16871229
user16871229

Reputation:

How to add list values in python

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

Upvotes: 1

Views: 76

Answers (4)

Niel Godfrey P. Ponciano
Niel Godfrey P. Ponciano

Reputation: 10719

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]

Upvotes: 2

Sheep Sven
Sheep Sven

Reputation: 1

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]

Upvotes: 0

I'mahdi
I'mahdi

Reputation: 24069

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]

Upvotes: 1

Prophet
Prophet

Reputation: 33381

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

Upvotes: 1

Related Questions