+ 1
for loop doubt
Given a list of numbers, calculate their sum using a for loop. Can this be achieved without using range??
9 odpowiedzi
+ 4
for el in my_list
for instance: el is the item in the list.
+ 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)
+ 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.
+ 1
Moreover, it is preferable not to use range() for such a task, but iterate over the list directly.
+ 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)
0
Santhosh Bharadwaj B S
if it's already in a list, why not just use sum()?
0
Omanshu This is a bad advice. No need to use enumerate() if you don't use the counter `i`.