# 15. Iterating over a list in a function... puzzled

#1

the code works. i got it to work by trying different things. i just dont understand the line i created..... lol

for x in range(len(numbers)):

i understand x will go through the whole list and numbers is part of the function. i don't see why i needed range and len.
if you could explain whats going on and why i needed it to make my function work i would be most appreciative
at do you expect to happen instead?>

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

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

print total(n)``````

#2

In other words this line is saying for as many numbers there are in the list, the following under the for loop needs to occur. It's necessary to have this line so that we can tell the function when to stop iterating over the list. I assume that answers your question....unless you are also confused on what `range` and `len()` signifies?

#3

why is range used. it seems undefined. it would be :Len. 0.0

#4

Hi,

Have you learned range in math? If not here's a link. The same the definition of range applies here. In this function, range is basically saying from the first to late number, here's what happens. Now since we want this function to work for any list, we use `len(numbers)` instead of the actual amount of items in the list. Without the range function, the code would never know when to stop, so that's why it is important. Do you understand?

Also I have no clue what you mean by this:

#5

I understand now. thank you, that was a big help

#6

Welcome. I'm curious though, what is this?

#7

he means would the len be 0

#8

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