+ 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)
11 Answers
+ 11
sum = 0
for n in x:
sum+=n
print(sum)
+ 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))
+ 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))
+ 4
You are welcome đ
+ 3
print(sum(x))
+ 2
print(sum(x))
# Keep learning & happy coding :D
+ 2
Jona Žonta
you said "calculate their sum using a for loop."
so JaScript is correct.
+ 1
Another popular way:
import reduce from functools
print(reduce(lambda a, b: a + b, x))
+ 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)
0
Jona Žonta
No worry just use sum function no need to use loop
print(sum(list1))
0
Best code