+ 1

for loop doubt

Given a list of numbers, calculate their sum using a for loop. Can this be achieved without using range??

30th May 2023, 7:28 PM
Santhosh Bharadwaj B S
9 odpowiedzi
+ 4
for el in my_list for instance: el is the item in the list.
30th May 2023, 8:20 PM
Lisa
Lisa - avatar
+ 3
Raymond don't use sum as variable name. It will override the Python sum() function and you can't use sum() later on in your program if you need to. arr = [3,6,7,9,0,35] #declare a "total" variable total = 0 #for loop used in list: for i in arr: total += i #now print the total print(total) #or don't use a for loop and just Python's sum() function. total2 = sum(arr) print(total2)
31st May 2023, 5:25 AM
Bob_Li
Bob_Li - avatar
+ 1
yes it can be achieved without using range() as Lisa said let's first understand what range() is doing , it just giving you the sequence of numbers to iterate upon and you are using it to access the elements from the list by index between you will learn in upcoming lessons of sololearn to make your own range() function.
30th May 2023, 8:29 PM
Ratnapal Shende
Ratnapal Shende - avatar
+ 1
Moreover, it is preferable not to use range() for such a task, but iterate over the list directly.
30th May 2023, 9:39 PM
Евгений
Евгений - avatar
+ 1
Yes, there are many ways you can do so. One of them is to use the enumerate function. Eg: arr = [2,3,4] sum = 0 for i,n in enumerate(arr): sum += n print(sum)
31st May 2023, 4:02 PM
Omanshu
Omanshu - avatar
0
Santhosh Bharadwaj B S if it's already in a list, why not just use sum()?
31st May 2023, 2:37 AM
Bob_Li
Bob_Li - avatar
0
Omanshu This is a bad advice. No need to use enumerate() if you don't use the counter `i`.
31st May 2023, 6:17 PM
Евгений
Евгений - avatar