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.
colors = ["red", "green"] colors[2] # IndexError: list index out of range
Try it
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.
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
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], orseq[-1]. A loopfor i in range(len(seq) + 1)is the classic bug. - Empty sequences have no first or last item; check
if seq:beforeseq[0]orseq[-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] = xfails on a 3-item list; useappend()orinsert(). - Prefer iteration.
for item in itemsorenumerate(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]) isTypeError, notIndexError. - Dictionaries raise
KeyError, notIndexError. CatchLookupErrorto handle both. - Other sources:
strindexing,bytes,array,sys.argv[1]when no argument was given, andre.Match.group(n)(no such groupisIndexError).