Search code examples
pythonlistsum

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


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

Solution

  • 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]