Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Tackling Lookup Error Exceptions

00:00 There’s another kind of exception you encounter when you’re looking for things that aren’t there. Lookup errors. These are found when dealing with Python containers.

00:08 You’ll look at two such exceptions in this lesson: the IndexError and the KeyError.

00:15 Back in the REPL, start by creating a list. colors = the list of the strings "red", "yellow", "blue", "pink", and "black".

00:28 And because list elements can be accessed by index, try to access colors at index eight.

00:36 IndexError: list index out of range. Because there are only five elements in this list, the largest index value is four. IndexError are pretty common, especially if you’re using code to generate the index to be accessed.

00:50 Often when you’re dealing with lists potentially increasing and decreasing their size and need to access specific indices or even ranges of indices, keeping track of the math of it all can be very complex.

01:02 It’s also an easy way to fall victim to off-by-one errors, for instance. If you slip up and forget that the first index of a Python list is zero and not one, and you’d be surprised how often this happens, even to Python veterans.

01:15 Now for a container that uses keys instead of indices like a dictionary, the exception to watch out for is the aptly named KeyError. To trigger a KeyError, again, you’ll need a dictionary.

01:28 Any dictionary will do, but I’ll make one whose keys are fruits.

01:33 fruits = the string "persimmon" with the value 4, the string "kumquat" with the value 3, and the string "tomato" with the value 5.

01:44 You’ll never guess what these numbers mean. And now if you take this dictionary and try to access the value associated with the key "grape", which does not exist, KeyError: 'grape'.

01:57 I find that one of the cases where this error happens most often is when dealing with ingesting data from web APIs or databases that sometimes can be inconsistent in their shapes or naming schemes.

02:09 A safer alternative to using the bracket accessing syntax would be to use the .get() method of dictionaries, which will return a default value if the key isn’t found instead of raising a KeyError.

02:20 And those were the lookup exceptions. They dealt with Python containers specifically, but might there be exceptions that pertain to Python objects in general?

02:29 Of course. Next up, object-related exceptions.

Become a Member to join the conversation.