0 points
Submitted by New User
over 6 years

# 15/18 Iterating over a list in a function Method 1

Since we aren’t modifying the list, feel free to use either one on this lesson! Create a function that returns the sum of a list of numbers. Create a function called total that adds up all the elements of an arbitrary list and returns that count, using the existing code as a hint. Use a for loop so it can be used for any size list.

My code is:

``````n = [3, 5, 7]
def total(numbers):
result = 0
for i in numbers:
result += numbers[i]
return result
print total(n)``````

Why it dosn’t work? err msg: Traceback (most recent call last): File “python”, line 8, in

I got no problem with Method 2

``````n = [3, 5, 7]
def total(numbers):
result = 0
for i in numbers:
result += i
return result
print total(n)``````
points
Submitted by spilogale
over 6 years

1 vote

you’re adding items to the original result so you only need it to look like

result += i

points
Submitted by Catherine Click
over 6 years

1 vote

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

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

print total(n)``````

Works both.

points
over 6 years

i will take on the numbers: 3 5 and 7 as the loop goes. using those numbers as indexes will cause index-out-of range. a for-loop does not produce indexes it directly supplies you with each element

points
Submitted by Jonatan
over 6 years

New User over 6 years

How code should look if we use method 1?

``enter code here``