Python List index out of range | What does mean & How to fix it?

If you try to access the empty or None element by pointing available index of the list, Then you will get the Python List index out of range error.

Simply: Index Error: List index out of range means you are trying to get an item in a list that doesn’t exist.

Python List index out of range

For Example, we have this list:

['z','x','y']

So ‘z’ is the 0th item, ‘x’ is the 1st, and ‘y’ is the 2nd.

You can get the value x by calling an index [1].

But if we call index [4], then index error happens. Because there is no 4th item, so it errors.

Example

Note: The list index starts from zero(0).

Output: IndexError: list index out of range

Q: How to fix the list index out of range in python?

Answer: To fix this error you have to use Python exception Handling.

Of course, you could also check the len() of dlist; but handling the exception is more intuitive.

Ternary

Test the length:

Python Loop: List Index Out of Range

We can fix this issue by iterating over a range of indexes instead:

for i in range(len(a))

and access the a‘s items like that: a[i]. This won’t give any errors.

Do comment if you have any doubts and suggestions on this tutorial.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Python 3.7
All Python Programs are in Python 3, so it may change its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.