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
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]
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]
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]