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.
Index Error: List index out of range means you are trying to get an item in a list that doesn’t exist.
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 .
But if we call index , 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)
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 except IndexError: gotdata = 'null'
Of course, you could also check the
dlist; but handling the exception is more intuitive.
gotdata = dlist if len(dlist) > 1 else 'null'
Test the length:
if len(dlist) > 1: newlist.append(dlist) 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)
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
All Python Programs are in Python 3, so it may change its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.