Index Error

Indices in Python

An index in Python represents a position in a sequence. Most commonly, this refers to a position in a string or a list. Indexing in Python, like most other programming languages, begins at 0. For example:

indexValueList = [0, 1, 2, 3, 4, 5]

Each value in this list also represents its own index. Note that the first item in the list is actually at index 0. Likewise, the maximum index into the list is equal to the length of the list minus one.

To access the element in a list at a given index, use the square bracket indexing notation like so:

>>> novels = ["Jane Eyre", "Wuthering Heights", "The Tenant of Wildfell Hall"]
>>> novels[0]
'Jane Eyre'
>>> novels[2]
'The Tenant of Wildfell Hall'

Note that negative indicies are also valid in Python. For example:

>>> novels[-1]
'The Tenant of Wildfell Hall'
>>> novels[-2]
'Wuthering Heights'
>>> novels[-len(novels)]
'Jane Eyre'

Strings can also be accessed by index. For example:

>>> name = "Brontë"
>>> print name[5]
ë

IndexErrors in Python

To encounter an IndexError in Python means that you tried to access an index of the list that doesn't exist. The range of valid indicies for any list is [0, 1, 2..n-1] where n is the equal to the length of the list. If you try to access anything greater than index n - 1, Python will throw an index out of range error:

>>> suits = ["Clubs", "Diamonds", "Hearts", "Spades"]
>>> print suits[4]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

For negative indexing, you cannot exceed the length of the list in the opposite direction. Namely, you cannot exceed index -n.

To determine the length of any sequence type, you can use the built-in len() function:

>>> len(["Elk", "Reindeer", "Sambar", "Moose"])
4
>>> len("Hat")
3

The len() function will return the number of elements in whatever sequence it is given as a parameter. To find the maximum allowable index for a sequence, simply subtract one from this number.

By far, the most common cause of IndexErrors in Python is being off by one index in either direction. Just remember, for a list of length n, the maximum allowable indicies are n - 1 in the positive direction and -n in the negative direction.