IndexError | Python’s Built-in Exceptions – Real Python

IndexError is a built-in exception that appears when you try to access an index that’s out of range for a sequence, such as a list, tuple, or string. You’ll see this exception whenever the index isn’t within the valid range of indices for that sequence.

You should be aware of this exception so you can debug your code effectively and avoid crashing your program when an invalid index is accessed.

IndexError Occurs When

  • Accessing an element in a sequence, such as a list, tuple, or string, using an index that’s out of range
  • Iterating over a sequence using indices that exceed the sequence’s length

IndexError Can Be Used When

Implementing custom sequence-like data structures that need to handle out-of-range indices.

IndexError Examples

An example of when the exception appears:

>>> colors = [
...     "red",
...     "green",
...     "blue",
... ]

>>> colors[10]
Traceback (most recent call last):
    ...
IndexError: list index out of range

An example of how to handle the exception:

>>> colors = [
...     "red",
...     "green",
...     "blue",
... ]

>>> try:
...     colors[10]
... except IndexError:
...     print("The index is out of range.")
...
The index is out of range.

For additional information on related topics, take a look at the following resources: