15. Why do we use range()


#1

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

In this tutorial it says that using either method is okay but, using Method 1 did not work.

Why is using range() here preferable than calling the list itself?

For instance, Method 2 which is this

for i in range(0, len(numbers)):

over Method 1 which is this

for i in numbers:

When I use Method 1 the error shows as: list index out of range.

This was the full one I wrote in case you were wondering:

n = [3, 5, 7]

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

total(n)

#2

but using a for in loop without range() gives the values directly from the list, range() will give a list with indexes:

n = [3, 5, 7]
for i in n:
    print i

for i in range(len(n)):
    print i, n[i]

#3

I tried to understand but to no avail... but I think the source of the problem is this:
Why is it that trying to print n[i] with the first for-in loop shows up as an error (list index out of range)?


#4

because using for in witout range will give you the values of the list directly, did you run the code i gave you?

n = [3, 5, 7]

for i in n:
    print i

see how i contains the values? (3, 5 and 7), so no need to access by index.


#5

Yep I ran the code you gave.

I think I couldn't understand at first since I forgot that for-in loop means n[i]. :sweat_smile:

Thank you so much for your help, I get it now. :slight_smile: I can do either this:

for i in numbers:
    result += i
return result

or this:

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

#6

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