explanation | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

explanation

hello all, can anyone explain why the output is 28. I thought the output would be the sum of all the characters in list. list = [4,6,8,3,7,9,5,3,] sum = 0 for a in range(len(list)): sum = sum + a print(sum)

20th Dec 2019, 2:36 PM
Abdelhakim Dahaman
Abdelhakim Dahaman - avatar
3 Answers
+ 9
There is no need to use range in the for loop here. And you should try to avoid using names like list for a variable name. lst = [4,6,8,3,7,9,5,3,] sum = 0 for a in lst: sum = sum + a print(sum)
20th Dec 2019, 3:04 PM
Lothar
Lothar - avatar
+ 3
a is always the number in the range, and you're adding that. Write: sum = sum + list[a]
20th Dec 2019, 2:50 PM
HonFu
HonFu - avatar
+ 3
len(list) returns the length of the list. Just simply use for a in list and it will be good. Btw, for loop in Python is like foreach loop in other languages
20th Dec 2019, 2:52 PM
你知道規則,我也是
你知道規則,我也是 - avatar