List index out of range


#1

Hi, I’m not sure if this is the right place to post this, but does anyone know why this code isn’t working? Thanks


n = [3, 5, 7]


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

It keeps saying list index out of range and I don’t know why
Thanks


FAQ: Learn Python – Lists and Functions – Printing out a list item by item in a function
FAQ: Learn Python – Lists and Functions – Printing out a list item by item in a function
#2

if we add a function call:


n = [3, 5, 7]


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

print_list([3])

we can see where it goes wrong, the problem is that len(n) will give 3, even if you pass a smaller list as argument to function call


#3

I tried copying your code, and it still didn’t work, but i replaced the 3 on the last line with n and it worked!!

Thank you so much for your help


#4

i would never post code that is the solution, my code was to add a function call so you could see the error message in the output window. Combined with some explanation to help you

do you understand why this works?


#5

I think it takes the amount of values in the n list, so would make sure that the function only runs while there are more values in the list to print, but I don’t know for sure. Is that why it works or is it because of something different?


#6

yes, but you don’t want this. Given you want to be able to pass a list of any size to the function.

understanding what x (function parameter) is, how it works, and how function arguments work is crucial:

n = [3, 5, 7]

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

# function calls with arguments
print_list(n)
print_list([3])
print_list([2, 4, 6, 8, 10, 12])

here is some code for you to study.


#7

ok thanks,
I don’t really understand what you mean to change, as when I added extra values to the n list, it still printed all the values.

Also with the example code you posted, does the first function call run the function normally, replacing all the x’s with values in the n list, with the second one saying to run replacing x with n up to the 3rd item in the list, and does the 3rd one replace n in the function with the items at the places in the list that you list seperated by the commas?


#8

because you changed len(n) to len(x), go change it back to len(n), see what happens. You will get errors, comment out print_list([3]), then you will see print_list([2, 4, 6, 8, 10, 12]) won’t print all its values

replace is not the right term here, function parameters get there values from arguments at function call. We just assign a different value to x every time.


#9

Ok, thank you so much, I think I get it now :grinning:


#10

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