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
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.
Answer 50beda440a703d06ba000e2d
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
1 comments
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
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.
Popular free courses
- Free course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner Friendly4 Lessons - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly11 Lessons - Free course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner Friendly6 Lessons