Search code examples
pythonfor-looplist-comprehensioncumulative-sum

Loop through list elements to get cumulative sums


I'm very new to python. I'm trying to create a loop so that I can get cumulative sums of the elements in a list. For example, given a list [3, 2, 1] I'm hoping to get [3 (first number), 5 (3+2), 6 (3+2+1)], [2 (second number), 3 (2+1)] and [1].

What I have currently is:

data = [5, 4, 3, 2, 1]
for i in data:
    perf = [sum(data[:i+1]) for i in range(len(data))]
    print(perf)

And I'm getting the following as output, which is the sum from the first element. How do I modify to get the cumulative sums starting with 4, 3, ... ?

[5, 9, 12, 14, 15]
[5, 9, 12, 14, 15]
[5, 9, 12, 14, 15]
[5, 9, 12, 14, 15]
[5, 9, 12, 14, 15]

My desired output

[5, 9, 12, 14, 15]
[4, 7, 9, 10]
[3, 5, 6]
[2, 3]
[1]

Thank you!


Solution

  • You're not far from the answer. You just need to begin your range from the next num in the list. Try this:

    data = [5, 4, 3, 2, 1]
    for ind, num in enumerate(data):
        perf = [sum(data[ind:i+1]) for i in range(ind, len(data))]
        print(perf)
    

    Output:

    [5, 9, 12, 14, 15]
    [4, 7, 9, 10]
    [3, 5, 6]
    [2, 3]
    [1]