Skip to content

[Solved][Python] IndexError: list index out of range

Last Updated on 2021-10-11 by Clay

This is a common problem when you beginning to learn python. The error is usually because you access the index but the index value is larger than python List length.

IndexError: list index out of range



Problem recurrence

The following is a sample code that repeats this error:

a = [1, 2, 3]
print(a[3])


Output:

Traceback (most recent call last):
  File "/Users/clay/Projects/PythonProjects/python_children_edu/test.py", line 2, in <module>
    print(a[3])
IndexError: list index out of range


We can see that the list we created has only 3 elements. According to the rule that the index starts from 0, the index value of the variable a is only 0, 1, 2.

So if we want to access index 3, python interpreter reported an error.

Yes, IndexErorr: list index out of range is just as the content: your index out of the list range.


Solution

In fact, there is only one solution: Do not use the index that exceed the length of the list.

For example, we modify the too large index value (3 to 2):

a = [1, 2, 3]
print(a[2])


Output:

3


We can find that the code is working properly.

But it should be noted that sometimes the error is not caused by the code we write; in many cases, we call other packages or modules and are not sure about the length of the list provided by them.

We use the too large index to call, so we get the error.

Therefore, you need to carefully check where the error occurred. The line number provided in the error message is also a good start point.

Don't doubt whether the error message provided by python are problematic, the python error messages are already more accurate than many programming languages.

Wish everyone a successful debugging.


References


Read More

Tags:

Leave a Reply