Index Errors

An IndexError means a sequence index is outside the valid range.

The list has three items, but the valid indexes are 0, 1, and 2.

The last index is always one less than the length:

The boundary rule

For a sequence with length n, valid indexes are:

0 through n - 1

So this loop is wrong:

range(0, len(items) + 1) produces 0, 1, 2, and 3. The final index is outside the list.

The fix is:

or, more often:

Empty lists

Empty lists have length 0. They have no first item:

Before reading the first item, check whether the list is non-empty:

Find the failing index

Runs locally with Python in your browser.

Ready to run.

The last printed index tells you where the boundary was crossed.

Slices are more forgiving

Indexing one item can fail:

items[10]

Slicing a range usually does not:

items[0:10]

That does not make slicing a fix for every bug. It only means Python can return the available part of a slice. If you expected ten items and got three, you still need to ask why.

Exercise: Last valid index

A list has length 5. What is its last valid positive index?

Answer it first, then check.

HintSubtract one from the length

Positive indexes begin at zero, so the last index is one less than the number of items.

SolutionThe last index is four

A length-five list has indexes 0, 1, 2, 3, 4. Its last valid positive index is 4.