Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Exceptions

Python IndexError

Reference for Python IndexError: list index out of range, off-by-one mistakes, empty sequences, why slicing never raises it, and safe ways to access items.

IndexError is raised when you use an integer index that is outside a sequence, such as a list, tuple or string. The familiar message is list index out of range.

Valid indexes for a sequence of length n run from 0 to n - 1, and from -1 to -n counting from the end. Anything else raises. IndexError is a subclass of LookupError.

Python
colors = ["red", "green"]
colors[2]   # IndexError: list index out of range

Try it

Python When it raises, and when it does not

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Safe access patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
item = sequence[index]

try:
    ...
except IndexError as error:
    ...
Name Description
index An integer; must satisfy -len(sequence) <= index < len(sequence).

Raises when: reading or assigning with an out-of-range index, or calling pop() on an empty list. Messages include list index out of range, string index out of range, tuple index out of range, list assignment index out of range and pop from empty list.

Usage notes

  • Off-by-one errors. The last item is seq[len(seq) - 1], or seq[-1]. A loop for i in range(len(seq) + 1) is the classic bug.
  • Empty sequences have no first or last item; check if seq: before seq[0] or seq[-1].
  • Slices never raise. seq[2:100] returns what exists, possibly an empty list. That also hides mistakes, so check lengths when it matters.
  • Assignment needs an existing slot. items[3] = x fails on a 3-item list; use append() or insert().
  • Prefer iteration. for item in items or enumerate(items) removes manual indexing and the error with it.
  • Changing a list while looping over its indexes can leave later indexes out of range.
  • Wrong type of index (seq["1"], seq[1.0]) is TypeError, not IndexError.
  • Dictionaries raise KeyError, not IndexError. Catch LookupError to handle both.
  • Other sources: str indexing, bytes, array, sys.argv[1] when no argument was given, and re.Match.group(n) (no such group is IndexError).