IndexError

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:

Python
>>> 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:

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

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

Tutorial

Python's list Data Type: A Deep Dive With Examples

In this tutorial, you'll dive deep into Python's lists. You'll learn how to create them, update their content, populate and grow them, and more. Along the way, you'll code practical examples that will help you strengthen your skills with this fundamental data type in Python.

intermediate data-structures python

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


By Leodanis Pozo Ramos • Updated March 13, 2025 • Reviewed by Martin Breuss