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?
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. The error occurs as soon as it hits
x as this is out of range, as are the other possibilities. In essence
i already contains the value you want.
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
n = [3,5,7] def myFun(n): for i in range(0,3): print n[i]
Don’t forget to change
x inside the function
Popular free courses
Learn SQLIn this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner friendly,4 LessonsLanguage Fluency
Learn HTMLStart at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner friendly,6 LessonsLanguage Fluency