Add previous value and carry the result in a list

Viewed 27

In Python, I am trying to add the to each number in a list, the value of the previous number and carry this sum through all of the list.

Given numbers = [2, 5, 3, 2], the output should be [2, 7, 10, 12], adding and carrying the sum until the end.

The following code is the one closest to the solution I managed to be, but I am getting [0, 2, 7, 10, 12], since I am starting with zero, but cannot find a different solution.

numbers = [2, 5, 3, 2]

newList = [0]
sumN = 0
for n in range(0, len(numbers)):
 sumN += numbers[n]
 newList.append(sumN)
print(newList)

Any help is appreciated.

1 Answers

Try this:

new_list = []

for i in range(len(numbers)):
    new_list.append(numbers[i] + sum(numbers[:i]))
Related