2

I am a beginner in python programming. I am trying to perform cumulative addition on values of a list.

values=[1,2,3]
for i in range(len(values)):
    print(sum(values[0:i]))

Output is

0
1
3

Whereas I am expecting a list with output [1,3,6]

Please can you someone guide me which part of my code is wrong? I don't wish to use accumulate() function.

Psytho
  • 3,313
  • 2
  • 19
  • 27

1 Answers1

0

You can also use walrus operator for python 3.8+

values=[1,2,3]
v=0
[v := v + n for n in values]

#output
[1, 3, 6]

Your corrected code should be from 1 to len(values)+1:

values=[1,2,3]
for i in range(1,len(values)+1):
    print(sum(values[0:i]))
1
3
6

Link : python-range

https://python-reference.readthedocs.io/en/latest/docs/functions/range.html

Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44