Python Printing out a list item by item in a function 12/18


The code prints out each item line by line, followed by
For some reason it throws the error message "list index out of range", even though it prints all the items in the list

Can anyone please tell me why my code doesn't work, or is it a bug?

 n = [3, 5, 7]

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


Try the following, and watch what happens:

print_list([2, 3, 4, 5, 6, 7, 8, 9, 10])


It gives the same error message


Not for the first one.

And the second one shows you that your function indeed doesn't do what it should.

You appeared to be confused about why your function appeared to work but codecademy said otherwise. Here, I gave you cases where your function isn't working so that you can see for yourself.


They both give that error message. I tried them by themselves and together.


No. The first one does not trigger that error message.

You can remove both and you'll get that error message from codecademy. But the first one isn't what causes it.

Look at how your function behaves differently from what it is supposed to do for those calls.


When I do the first one by itself, at the bottom of the screen it gives the same error message, but in the console it says that i gave too many arguments.


Your function takes one argument and both my calls have one argument. Perhaps you copied them incorrectly by hand instead of using your OS's clipboard feature. Or perhaps you have some other function call that triggers that error.


Sorry I made a mistake in the copying, the first one works now? But why does it still say i have an error at the bottom of the page, even if the list at the beginning prints in the console?


Does it work? How many numbers are printed? It should print them all, right? That's the purpose of the function

Your observations are all over the place, you can't draw any good conclusions from them if they are not accurate!


OK so for some reason when I run the first line with 9 integers, it only prints the first three.


And what happens if you print the first three values of the second one?


Sorry, I don't understand. In the second one, there is only one value, right?


Yeah. So what happens if you print the first three?


print_list([2, 3, 4])
You mean like this?


no, the first three of [2]

my_list = [2]
print my_list[0]
print my_list[1]
print my_list[2]

What happens


I just face palmed so hard. I realised that I forgot to change n to x in my original code. I feel like such an idiot.


And we're gonna make mistakes like that all the time.

Sometimes we can be extra careful, sometimes we can review small amounts of code for its correctness.

Other times, we need to be able to systematically find where the problem is.


Thank you so much!:joy:


This topic is solved.