← Go Back

How to Fix IndexError: list index out of range

Python throws the IndexError exception when trying to access the index of an element that is not inside a list or tuple, for example:

>>> # Index:    0    1    2
>>> my_list = ["a", "b", "c"]
>>> my_list[0]
'a'
>>> my_list[2]
'c'
>>> my_list[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range

To fix this, make sure that the list is not empty and that the index indicated in square brackets is between 0 (first element) and len(my_list) - 1 (last element).

lists tuples


🐍 You might also find interesting: