Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

IndexError — sequence index out of range

IndexError is a built-in exception raised when an attempt to access a sequence element uses an out-of-range index. Learn valid index bounds, the difference between indexing and slicing, and how to catch this exception.

Version: Python 3.14; repository image, production runtime not attested

Syntax

sequence[index]
try:
    sequence[index]
except IndexError:
    ...

IndexError means that a sequence element index is out of range. This applies to lists, tuples, and strings, for example. It is a subclass of LookupError; a missing dictionary key instead causes KeyError.

For a built-in sequence s of length n, valid integer indices satisfy -n <= i < n. Index 0 selects the first element, and -1 selects the last. An empty sequence has no valid element index. A common mistake is using s[len(s)]: the last element of a nonempty sequence has index len(s) - 1.

Indexing and slicing are different operations. For the example list, items[3] raises IndexError, but items[3:] returns an empty list: slice bounds are clipped to the sequence's range. An unsupported index type, such as a string used to index a list, causes TypeError, not IndexError.

If a missing element is an expected situation, catch IndexError in a narrow try block around the relevant access. If it indicates a programming mistake, fix the index calculation rather than hiding it. When you only need element values, consider iterating directly over the sequence.

Examples

items = [10, 20, 30]
print(items[-1])
print(items[3:])

try:
    print(items[3])
except IndexError:
    print("IndexError")

Result

30
[]
IndexError

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources