Exceptions

Published

2023-07-31

Exceptions

IndexError

When dealing with sequences, you may encounter IndexError. This exception is raised when an integer is supplied as an index, but there is no element at that index.

>>> lst = ['j', 'a', 's', 'p', 'e', 'r']
>>> lst[6]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

Notice that the error message explicitly states “list index out of range”. In the example above, we have a list of six elements, so valid indices range up to five. There is no element at index six, so if we attempt to access lst[6], an IndexError is raised.

TypeError

Again, when dealing with sequences, you may encounter TypeError in a new context. This occurs if you try to use something other than an integer (or slice) as an index.

>>> lst[1.0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not float
>>> lst['cheese']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not str
>>> lst[None]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not NoneType

Notice that the error message explicitly states that “list indices must be integers or slices” and in each case, it identifies the offending type that was actually supplied.

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).