IndexError
is a type of error in Python that occurs when you try to access an index that is out of range for a list, tuple, or string. In other words, you are trying to access an element in a sequence using an index that does not exist.
For example, if you have a list with 5 elements and you try to access the element at index 5 (sequences are indexed starting at 0), you will get an IndexError
because the index is out of range.
Here’s an example of how you might encounter an IndexError
:
my_list = [1, 2, 3, 4, 5] print(my_list[5])
Output:
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[8], line 2 1 my_list = [1, 2, 3, 4, 5] ----> 2 print(my_list[5]) IndexError: list index out of range
To avoid this error, make sure that the index you are using is within the range of the sequence.
The following tutorials cover some of the common IndexErrors in Python and how to resolve them with the help of some examples.