Both IndexErrors
and KeyErrors
are subclasses to the more general LookupError
. IndexError
is commonly encountered when working with lists. This error occurs when the program is attempting to access a position that is not indexed by the object. For example, attempting to access the fifth index of a list with three elements will fail.
Recreating the error and going step by step through the faulty function, either by debugging with an IDE or manually in the interactive prompt, can help give a better understanding of where the error is coming from and how to fix it. See the following code:
>>> small_list = ['a', 'b', 'c', 'd'] >>> print small_list[4] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range # Check the max index value >>> print len(small_list) - 1 3
IndexErrors
are generally easily solved; simply check the number of indices in the object by using the built-in len
function. Remember to subtract 1 from the result as an index begins with 0 while len
starts counting at 1.