+ 4

Sum of list?

#Given a list of numbers, calculate their sum using a for loop. x = [42, 8, 7, 1, 0, 124, 8897, 555, 3, 67, 99] #Here is the solution which works (there's a tab before print): for m in x: print(x[0]+x[1]+x[2]+x[3]+x[4]+x[5]+x[6]+x[7]+x[8]+x[9]+x[10]) break #However, firstly I tried to do the following, but the result is 42, 50, 57 and so on. How to express only the final sum, not the whole list (but with little code?) sum = 0 for n in x: sum+=n print(sum)

4th Nov 2021, 11:32 AM
Jona Žonta
Jona Žonta - avatar
11 Antworten
+ 11
sum = 0 for n in x: sum+=n print(sum)
4th Nov 2021, 11:44 AM
JaScript
JaScript - avatar
+ 5
SoloProg okay so I did kind of googled that and gave up but only now I realised why it didn't work - because I already used the "sum" as a name I think. If I change it, both solutions work. sumzz = 0 for n in x: sumzz+=n print(sumzz) #or print(sum(x))
4th Nov 2021, 12:13 PM
Jona Žonta
Jona Žonta - avatar
+ 4
JaScript Ohh this is brilliant, I should have just put the print bellow the for (without a tab). Thanks. (ironically in my comment to the first solution I was also talking about the tab before print - but because of other reasons (I wasn't sure how my long line would be copy pasted))
4th Nov 2021, 11:50 AM
Jona Žonta
Jona Žonta - avatar
+ 4
You are welcome 😊
4th Nov 2021, 11:53 AM
JaScript
JaScript - avatar
+ 3
print(sum(x))
6th Nov 2021, 1:48 AM
CGO!
CGO! - avatar
+ 2
print(sum(x)) # Keep learning & happy coding :D
4th Nov 2021, 12:07 PM
SoloProg
SoloProg - avatar
+ 2
Jona Žonta you said "calculate their sum using a for loop." so JaScript is correct.
4th Nov 2021, 12:33 PM
SoloProg
SoloProg - avatar
+ 1
Another popular way: import reduce from functools print(reduce(lambda a, b: a + b, x))
5th Nov 2021, 3:25 PM
Yahel
Yahel - avatar
+ 1
you can do it with the iterative version or recursive version https://code.sololearn.com/cY8t5z0SMjA1/ ps: or use a builtin function like sum(arr)
6th Nov 2021, 9:31 AM
Pere Antoni Rollon Baiges
Pere Antoni Rollon Baiges - avatar
0
Jona Žonta No worry just use sum function no need to use loop print(sum(list1))
4th Nov 2021, 12:59 PM
A͢J
A͢J - avatar
0
Best code
5th Nov 2021, 3:23 PM
Aditya Pardeshi
Aditya Pardeshi - avatar