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.
What IndexError means
IndexError: list index out of rangeA 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, notlen(items). Useitems[-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 whenitemsis[].
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.
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.
songs = ["Intro", "Neon Rain", "Static", "Outro"]
for i in range(1, len(songs) + 1):
print(i, songs[i])