# 15.Iterating over a list in a function

#1

Hey guys, so i've completed the exercise by trial and error, i coulnd fint anyone using the 2nd method using the range().
My problem is that i still don't understand step by step how the programs read it. If someone could take the time to maybe write it down the way the programs reads it so my brain can understand.

Thank you

``````n = [3, 5, 7]

def total(numbers):
result = 0
for x in range(len(numbers)):
result = result + numbers[x]
return result``````

#2

Nobody uses this method because we don't need the index, only the item. A simple look-up loop is sufficient.

``````result = 0
for x in numbers:
result += x``````

In the above, x is the value or item in the list.

``````for x in range(len(numbers)):
result += numbers[x]``````

In the above, x is the index, and numbers[x] is the value.

#3

Alright, which is why i had trouble then finding that i needed to specify the index in:

result += numbers[x]

i thought it would be good to use the new method since they were teaching it but true the index is useless in this exercise.

thank you

#4

I wouldn't say useless, especially if that is what the lesson is about. Will need to check the lesson. Please post a link so I can double check. One does not want to be giving invalid advice.

#5

#6

So we are essentially free to choose which approach we want to use. Generally, the look-up approach is adequate when no alteration is taking place. When altering items in the list, the index (range) approach is the one to reach for.

#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.