Home > other >  Summing consecutive elements in a list and appending to a new list
Summing consecutive elements in a list and appending to a new list

Time:02-11

Consider the list:

a = [1,2,3,4,5]

How can I iterate through this list summing the consecutive elements and then producing a new list as follows:

b = [1,3,6,10,15]

such that each element in list b is the sum of all the prior elements up to that index number from list a. i.e. b[0] = a[0], b[1] = a[0] a[1], b[2] = a[0] a[1) a[2] etc.

This is merely pseudo-code. In reality, my real list 'a' has thousands of elements, so i need to automate; not just write b[1] = a[0] a[1] and do that for the 5 elements of b. Any ideas would be greatly appreciated: I am new to python.

CodePudding user response:

You could use list comprehension as follow:

a = [1,2,3,4,5]
b = [sum(a[:i 1]) for i in range(len(a))]

CodePudding user response:

If you're willing to use numpy this is just the cumsum function:

import numpy as np
a = [1,2,3,4,5]
np.cumsum(a)
# array([ 1,  3,  6, 10, 15], dtype=int32)
  • Related