Brainlag
  1. Library
  2. Debugging
  3. Python

IndexErrorWhat is an IndexError?

An IndexError means you asked a list or string for a position that does not exist. Usually off by one, or the list is shorter than you think.

Python5 min

What IndexError means

Output
IndexError: list index out of range

A list of 4 items has the indexes 0, 1, 2 and 3. Ask for index 4 and there is nothing there, so Python stops. Strings do the same: "abc"[3] is an IndexError.

The usual causes:

  • Counting from 1. The last item is at len(items) - 1, not len(items). Use items[-1] for the last one.
  • A range that runs one too far. range(1, len(items) + 1) used as indexes.
  • An empty list. items[0] fails when items is [].

How to find it

Read the line number, then find the [...] on that line. Work out two things: what index it asked for, and how long the list really was at that moment. Add print(i, len(items)) just above the line if you are not sure. If the index equals the length, you are off by one.

Run it: one past the end

Press Run and read the error from the bottom up.

main.py to run
squad = ["Ana", "Ben", "Cleo"]
print(squad[0])
print(squad[3])

The tracklist that runs off the end

This should number the songs 1 to 4. It prints the wrong songs and then crashes. Keep the numbers starting at 1 and fix the indexing.

exercise_1.py to run
songs = ["Intro", "Neon Rain", "Static", "Outro"]
for i in range(1, len(songs) + 1):
    print(i, songs[i])

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.