'Summing consecutive elements in a list and appending to a new list [duplicate]
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.
Solution 1:[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))]
Solution 2:[2]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jenny |
| Solution 2 | Kraigolas |
