What Causes an IndexError in Python
- Accessing Non-Existent Index: When you attempt to access an index of a sequence (such as a list or a string) that is out of range, an Indexerror is raised. Sequences in Python are zero-indexed, which means that the first element’s index is 0, the second element’s index is 1, and so on.
- Empty List: If you try to access an element from an empty list, an Indexerror will be raised since there are no elements in the list to access.
Example: Here our list is 3 and we are printing with size 4 so in this case, it will create a list index out of range.
Python3
j = [ 1 , 2 , 4 ] print (j[ 4 ]) |
Output
print(j[4])
~^^^
IndexError: list index out of range
Similarly, we can also get an Indexerror when using negative indices.
Python3
my_string = "w3wiki" print (my_string[ - 61 ]) |
Output
print(my_string[-61])
~~~~~~~~~^^^^^
IndexError: string index out of range
Python List Index Out of Range – How to Fix IndexError
In Python, the IndexError
is a common exception that occurs when trying to access an element in a list, tuple, or any other sequence using an index that is outside the valid range of indices for that sequence. List Index Out of Range Occur in Python when an item from a list is tried to be accessed that is outside the range of the list. Before we proceed to fix the error, let’s discuss how indexing work in Python.
Contact Us