Calculating the cumulative sum in a list starting at the next element and going through the list in Python

Question:

Let’s say I got a list like this:

L = [600, 200, 100, 80, 20]

What is the most efficient way to calculate the cumulative sum starting from the next element for every element in the list.

The output of should thus be:

 x_1 = 400 (200 + 100 + 80 + 20)
 x_2 = 200 (100 + 80 + 20)
 x_3 = 20 (20)
 x_4 = 0
Asked By: Steven01123581321

||

Answers:

You can use the sum functio
sum(L)-L[0]

Answered By: pythonista

try this:

    l = [600, 200, 100, 80, 20]
    res = [sum(l[i:]) for i in range(1, len(l))]
    print(res)

for your example the output should be [400, 200, 100, 20]

Answered By: Daniel
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.