12. Printing out a list item by item in a function "list index out of range"


#1


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


"Oops, try again. Your function caused the following error: list index out of range"


I think this is bugged. Even when I remove my code and submit what was already in the lesson, it gives me that error.


#This code was already here
n = [3, 5, 7]

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

#My code starts here    
def print_list(x):
    print x[0]
    print x[1]
    print x[2]
    
print_list(n)


#2

That function ignores the length of the list and attempts to print the first three elements regardless if they exist or if the list is longer than that.

"print a list"
and
"print the three first elements of a list"

Are different actions


#3

The code that was already there will print out every item in a list called 'n,' but it is not useful for much else. A more useful bit of code would be one that allows you to print out every item in any list presented. What you want to do here is to take the code on lines 3 & 4 and put it inside of a function.

Delete from your function:

    print x[0]
    print x[1]
    print x[2]

because this will only ever print out the first three items in a list, what if the list is longer than three items?

Replace it with:

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

but don't forget to replace the n's with x's(because that is the name of the function's argument) and adjust the indentation. Don't forget to check out the instructions and hints in each lesson. They can be helpful.


#4

n = [3, 5, 7]

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

doesn't change anything really! i inteded correctly but for some reason it doesnt show up here


#5

See here on how to post code in the forums. Your for loop needs to be inside of your function.


#6

I ran into the same thing. After rereading the instructions I figured it out. I need to add this bit at the end, outside of the function.

print_list(n)

#7

the for loop needs to be inside the function.

n = []

def print_me () :
for loop....

try it this way


#8

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