1

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.

bjuksel
  • 33
  • 3

2 Answers2

-1

You could use list comprehension as follow:

a = [1,2,3,4,5]
b = [sum(a[:i+1]) for i in range(len(a))]
Jenny
  • 601
  • 3
  • 11
-1

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)
Kraigolas
  • 5,121
  • 3
  • 12
  • 37