This forum is now read-only. Please use our new forums! Go to forums

0 points
Submitted by William Trumble
almost 11 years

IndexError: list index out of range

n = [3,5,7]

def myFun(x):
    for i in x:
        print x[i]

myFun(n)

Traceback (most recent call last): File “python”, line 7, in


I was playing around with this exercise, trying to get the same output a different way. Why do I get this error? Is it because ‘i’ starts at 1 and the list starts at 0?

Answer 50c88d4ebd90665ae7004d2a

5 votes

Permalink

i is the value and not the position, looping through the list [3, 5, 7], i would first equal 3, then 5 and finally on the third iteration 7. Depending where you are in the loop by doing x[i] you are saying x[3], x[5] or x[7]. The error occurs as soon as it hits x[3] as this is out of range, as are the other possibilities. In essence i already contains the value you want.

points
Submitted by Robert
almost 11 years

Answer 50beda440a703d06ba000e2d

1 vote

Permalink

One thing I’ve noticed is that the indentation character (presumably a tab) must be there for the code to run properly. I took the original code in step 1:

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

and stuck it in a function and I received the same error you received. When I positioned myself on the end of the for statement line and hit the delete key until the next line was immediately after the for statement, I hit the “Enter” key [CRLF] to recreate the indentation and the error went away.

This code works without errors, as long as I regenerate the CRLF->tab after the for statment.

n = [3,5,7]
def myFun(n):
    for i in range(0,3):
        print n[i]

Don’t forget to change n to x inside the function

points
Submitted by Stuart Connall
almost 11 years

1 comments

Dayton over 10 years

I find it frustrating that you need to regenerate the CRLF->tab as you mention. I was working on this problem with working code for 20 minutes. I read your comment and it fixed it. Is this a general Python issue or a Codecademy editing window issue?

Answer 50c85c59bd6c7b1c25002f44

1 vote

Permalink

x[i] is the ith element of x.

Your code is, the first time in the loop, trying x[3], which is out of bounds of the array.

points
Submitted by Josh O'Brien
almost 11 years