Why do we need to use range() in step 12 and 13?


#1

Hey, I'm wondering...

In 12. Printing out a list item by item in a function...
https://www.codecademy.com/courses/python-beginner-nzzVa/3/1?curriculum_id=4f89dab3d788890003000096

How come you have to write range() at all? Why doesn't for i in x work? i.e.:

n = [3, 5, 7]

def print_list(x):
    for i in x:
        print x[i]
        
print_list(n)

It throws the following error:

Traceback (most recent call last):
File "python", line 7, in
File "python", line 5, in print_list
IndexError: list index out of range

In previous lessons like A Day at the Supermarket this wasn't the case:
https://www.codecademy.com/en/courses/python-beginner-en-IZ9Ra/0/1?curriculum_id=4f89dab3d788890003000096


#2

Find out what x and i refer to in your loop


#3

That doesn't really help. I guess what I'm asking is what the difference is between:

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

and

    for i in x:
        print i

#4

Just print out what x and i is in your loop.
To find out you have to look. To look at a variable, print it.
And when you have seen what x and i are, re-consider what you can/want to do with them.


#5

You can also consider what this does:

x = range(5)
for i in x:
   print i

#6

x = range(5) seems to be the same as x = [0, 1, 2, 3, 4]
The loop does the same for either one, anyway.

I see now that if I actually submit with

    for i in x:
        print i

it gives a different error "Oops, try again. This lesson has been recently modified to use 'len'. Please hit reset and try again."

So for the purposes of this task there isn't actually a difference? I understand that you'd use range if you only wanted a section of the array, but in this case you want the whole thing.


#7

That's what the range function returns for an argument of 5, yes. And you can loop through that to get numbers counting up from 0.

As for what the exercise wants you to do, just follow as closely as possible while keeping in mind that what what matters is not what the exercise accepts but that code behaves the way you intend. So compare behavior with your expectations, and if it's not accepting something, try following the instructions more closely, remove the smallest differences you can find.

If the purpose of a loop is to iterate through an iterable, then it's very redundant to create a second iterable for the sake of iterating through the first one. (What's to stop you from creating a third for iterating through the second?)


#8

Well, I think I understand a bit better how this works now. Thanks for your time!