-1

Suppose I have this list. list1 = [1,2,3,4,5,6] and I want to find sum of elements of list1 but each time I want too see the sum. Namely to make new list like this sum1 =[1,3,6,10,15,21]. How can I do it with for loop?

  • 1
    Does this answer your question? [How to find the cumulative sum of numbers in a list?](https://stackoverflow.com/questions/15889131/how-to-find-the-cumulative-sum-of-numbers-in-a-list) – Brian61354270 Mar 22 '21 at 16:00

2 Answers2

0
list = [1, 2, 3, 4, 5, 6]
sum_list = []
sum = 0
for element in list:
    sum = sum + element
    sum_list.append(sum)

Hope this works :)

bad_coder
  • 201
  • 1
  • 9
-1

You can use indexing along with sum

l2 = [sum(list1[:i+1]) for i in range(len(list1))]

print(l2)

Output:

[1, 3, 6, 10, 15, 21]
Sociopath
  • 13,068
  • 19
  • 47
  • 75