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


#1




i get the following error: "list index out of range"


to me this error means that (0, len(x)) is too great a range since the list "n" contains 3 elements the 0 to len(x) would represent 0 to element 3, because there are 3 elements. but the range 0 to 3 is the range for a 4 element list. so i tried (0, len(x)-1) but ot the same error message. i ve searched the forum but no joy. so what am i doing wrong here?


n = [3, 5, 7]

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


#2

if you want to place a for loop inside your function you will need to indent it:

def example(s):
    for k in s:

if you need more help, post an updated version of your code


#3

yes of course. now it works. however i am confused about the len(x) part.does len(x) in this case not equal to 3 since len(something) returns the number of elements in a list? therefore this would tell the program to process the list of 3 elements to an extent of 4 elements? i.e. range(0,3) which is 4 elements 0, 1, 2, and 3


#4

yes, it does. so if your list is n = [3, 5, 7], len(n) will give 3.

the trick is actually in range(), range(0,3) would give: 0, 1, 2

range does not include its stop value (in this case 3).

so range gives values lesser then (<) the stop value, not lesser or equal to (<=) the stop value. (i always find this a useful way to remember it)


#5

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