15. Iterating over a list in a function



Oops, try again. total([0, 3, 6]) returned 3 instead of 9

I honestly thought the code would work. I assume that the variable x represents all indexes in numbers but if the error code is saying it only returns 3, then x either isn't adding all the indexes together or does not represent all of them.

n = [3, 5, 7]

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


x contains indexes, not actually items of the list because you use range()

either don't use range(), or use x as index to get items of the list


Ok so If I change
result = result + x


result = result + numbers[x]

Then that would work since when you use range, x is contains all indexes but needs to be called like an index?


result = result + numbers[x] should work, yes, because x contains the index, by using square brackets you can use x as index to retrieve items from the list


ok so by creating the for with range statement I have created a list called numbers and x represents all indexes in that list. But if I used a for statement without the range I wouldn't need to call x with brackets because I didn't make a list?


we have a list stored in numbers, we can loop over numbers to get the items of the list:

for x in numbers:
   print x

we can also use range(), range() will gives us a list:

for x in range(len(numbers)):
   print x

we can also see that range gives us a list:

print range(len(numbers))

this list has numbers which matches indexes of our numbers list:

for x in range(len(numbers)):
   print numbers[x]


Ok awesome thank you very much! You really cleared up what I was confused about. :grinning:

I wish you good fortunes in the wars to come.