15/18 Iterating over a list in a function


#1

Exercise 15/18:

I got stuck at this exercise, but managed to solve it at last. My goal was to be able to use both method 1 and method 2. See explanation to both methods below the code.

Method 1:

n = [3, 5, 7]

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

print total(n)

Method 2:

n = [3, 5, 7]

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

print total(n)

The difference between using the both:
I think it's beacuse range allows for looping through the index numbers, which in this case is up to, but not including 3. Index 0, 1, 2. Thus result += numbers[i] will be the same as result += n[index]. n[index] in turn represents the value at the given index in the n list. Basically, range allows for assigning the index numbers of a list to variable i.

Whilst when using for i in numbers:, the for loop will iterate through the actul values of the list to the variable i. Thereby we only need to write reseult += i.

I thought this could be useful for those who get stuck at this step. I'm new at programming, so please correct me if my assumptions are wrong.


#2

the correct way of saying this: range() gives us a list of numbers, which we perfectly match with the indexes of numbers list.

range() thankfully very friendly, it gives values lesser then (<) the stop value. so if we have a list which has 3 items, the length (thus the stop value) is 3, so values lesser then 3, which perfectly matches the indexes


#3

Cool, thanks man. That makes much more sense :slight_smile:


#4

it does, doesn't it? Range is a built in function, but of course designed to work nicely for lists indexes, but it is still a list:

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

print total(n)

#5

You have labelled your programs the wrong way round.
First program using the range() function is Method 2 and second program is Method 1 as per the unit instructions.


#6

What does += do? I don't recall seeing that yet.


#7

this must be covered? its a shorthand for:

result = result + numbers[i]

i am 99% sure this is covered


#8

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