15. Iterating Over a List in a Function - Can't get the second method


#1



https://www.codecademy.com/courses/python-beginner-nzzVa/3/4?curriculum_id=4f89dab3d788890003000096

I was trying out both methods for iterating. The first method I did yields the correct answer and it's as follows:

n = [3, 5, 7]

def total(numbers):
-result = 0
-for i in numbers:
--result = result + i
-return result

print total(n)

But when I try the second method the numbers don't seem to add up. Here's the code:

n = [3, 5, 7]

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

print total(n)

I get an error saying (Oops, try again. total([0, 3, 6]) returned 3 instead of 9).

Shouldn't the code range(len(numbers)) equal range(0,2) in this case and it should iterate through all the three numbers to return a sum? Gosh I'm so confused...

Thanks guys, any help is great!


Replace this line with your code.


#2

range creates a list, when you iterate through a list, the loop variable will have each element of that list assigned to it, one at a time. So which list's elements are getting assigned to i? You can also print it out to see what happens.


#3

i'm having the same problems.... got it with the 1st method, and im trying to find a fix for the second one.

I don't quite understand what @ionatan is trying to explain.


#4

I think i got it...

when using only

for x in numbers

the result will be stored in the result.

but when using

for x in range(len(numbers)):

you have to specify the position of the number to add to the result?

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

does that make sense???


#5

My code looked like this minus the + result. Can you explain why you need to add result to make it work?

for x in range(len(numbers))

This will iterate through the parameter numbers (good so far)

result = numbers[x]

I thought this will take each number in the list and add it to the new list called result. But what does the + result do (result = numbers[x] + result)?

Thanks,

Melissa


#6

hi,
when you have only
result = numbers[x]

what you are doing is only replacing the value o fthe variable "result" with whatever is stored in 'numbers[x]'. So that value is going to change with every iterarion.
But, when you have
result = numbers[x] + result

you are adding whatever value is stored in 'result' to the value of 'numbers[x]' in that given iteration. Therefore what your have is like a running total, the total sum of 'numbers[x]'.

is that more or less clear?


#7

remember that variables can change numbers at any time:

x = 1
x = 4
print x
4

or

x = 1
x = x + 4
print x
5

#8

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