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:


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 List index out of range in Python

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

nums = [14, 5, 4, 5, 7, 32, 5]


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.

    gotdata = dlist[1]
except IndexError:
    gotdata = 'null'

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


gotdata = dlist[1] if len(dlist) > 1 else 'null'

Test the length:

if len(dlist) > 1:

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.