-2

I'm trying to create a function that takes a list as an argument and then gives back a new list with the cumulative sum of that list. For example:

l = [1, 7, -3, 9, -2]

would become:

[1, 8, 5, 14, 12]

I am also trying to use a for loop for this function.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61

2 Answers2

2

Python makes this super easy:

>>> l = [1, 7, -3, 9, -2]
>>> [ sum(l[:n+1]) for n in range(len(l)) ]
[1, 8, 5, 14, 12]
Lewis
  • 4,285
  • 1
  • 23
  • 36
1

Use itertools.accumulate:

>>> from itertools import accumulate
>>> list(accumulate([1, 7, -3, 9, -2]))
[1, 8, 5, 14, 12]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • Why do you answer a question you vote to close, as a duplicate, with that answer in the dup? kinda beats the purpose of closing – Tomerikoo Feb 20 '20 at 00:19
  • @Tomerikoo I answered before I voted to close. This answer's still useful cause it shows OP exactly how to get what they want. – wjandrea Feb 20 '20 at 00:32
  • Like this and many more answers in the dup... That's the point of duplicates, close the question for new answers, as there are already plenty to help OP in the link – Tomerikoo Feb 20 '20 at 00:33