-2

Say I have a list (This list can have any amount of numbers):

a = [2,5,2,4]

I want to reverse that:

a[::-1]

which gives me [4,2,5,2]. Then I want to achieve the sum of the first number, the sum of the first 2 number, the sum of the first 3 number etc. So I should get:

[4,6,11,13]
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
iamapc
  • 69
  • 5

1 Answers1

0

You need to use a for loop.

>>> m = []              # creates an empty list
>>> j = 0               # Declare a variable and assign 0 to it. This would be used to store the calculated intermediate sum.
>>> for i in a[::-1]:   # iterate over each item in the reversed list. 
        j += i          # For each iteration, add the element with the j value and then assign the result back to the variable j.
        m.append(j)     # Append the content of j to the list m.


>>> m
[4, 6, 11, 13]
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274