How to find the sum of the sum of numbers in a given list in Python 3? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to find the sum of the sum of numbers in a given list in Python 3?

There are N numbers in a list. We need to find the sum of the numbers from the start till the position of the list and then add that sum to the total. I have a code below which is slower than the expected solution. def fun(lst): total, till_now = 0, 0 for i in lst: till_now += i total += till_now return total Please help to make this code faster! Thank you so much!

22nd Sep 2019, 9:27 AM
Hermione
Hermione - avatar
5 Answers
+ 3
your codes does give result of 20 if i use list [1,2,3,4]. so i build a code that does the same: def sum_(lst): total = 0 for ind in range(len(lst)): #both for loops does work #for ind, i in enumerate(lst): total += sum(lst[:ind+1]) return total print(sum_([1,2,3,4]))
22nd Sep 2019, 12:24 PM
Lothar
Lothar - avatar
+ 1
sum(list) You want to add the numbers in a list?
22nd Sep 2019, 9:33 AM
Trigger
Trigger - avatar
+ 1
Did you mean to find the sum of all elements in a list? def fun(lst): total = 0 for i in range(0, len(lst)): total += lst[i] return total
22nd Sep 2019, 9:38 AM
Peter Parkers
Peter Parkers - avatar
+ 1
I meant to say that first I need to calculate the sum of the numbers from the start of the list till the position that I am at and then the total sum of those sums. For example, if lst = [3, 4, 5] first it should be lst[0] reading 3, lst[1] reading 3 + 4 = 7, lst[2] reading 3 + 4 + 5 = 12 so the expected answer is 3 + 7 + 12 = 22
22nd Sep 2019, 9:52 AM
Hermione
Hermione - avatar
+ 1
Thank you @Jay Matthews
22nd Sep 2019, 10:25 AM
Hermione
Hermione - avatar