# 15. Iterating over a list in a function

#1

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

It should work as I could see other people writing same code.

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

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

print total(n)``````

#2

You really overcomplicate things.

what do you expect this to do? you just need to say

``for i in numbers:``

because numbers is an array. Arrays can be iterated through as well as strings.
inside of the function total(), you need to make result equal to result plus i like this:

``result += i``

Now, let's talk about what you're trying to do. This is not a manual for loop that needs a starting point, an ending point, and an increment. You use for each loops to iterate through lists, arrays, strings, etc. Whenever you see the word "iterate", you know to use one of these. The problem is that you think i is a number that increments. i is actually each item in a list. So i is 3, 5, and 7 when you pass it the array, n, and result needs to be equal to the sum of the array by adding i to result each time.
I hope this helps a little.

#3

Be sure the return statement is not inside the loop. It is returning on the first iteration.

#4

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