Skip to content

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

  • by

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

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

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

print(nums[10])

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.

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

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

Ternary

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

Test the length:

if len(dlist) > 1:
    newlist.append(dlist[1])
    continue

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

Your email address will not be published. Required fields are marked *