Python LookupError – Tutorial with Examples

Python LookupError - Tutorial with Examples

In Python, LookupError is a standard exception raised whenever an invalid loopup operation is performed, mostly while accessing keys that are non-existent in a dictionary or a set. LookupError is a base class of exceptions like KeyError, IndexError, and others.

This tutorial will provide an explanation of the LookupError in Python and its usage with examples. It will also cover various subclasses of LookupError and how they are raised.

Handling LookupError

Python’s LookupError exceptions are raised automatically when the interpreter encounters an error while performing a lookup operation on a dict, list, tuple, or set.. You can also raise LookupError exceptions in your code if you think an error might occur with the Lookup operation.

The following example shows the handling of LookupError in python:

fruits = {'apple': 2, 'banana': 4, 'orange': 1}

try:
    fruit = fruits['mango']
    print(fruit)
except LookupError:
    print("Fruit does not exist.")

Output:

Fruit does not exist.

LookupError Subclasses

LookupError has some commonly used subclasses that inherit the base class’ behaviour but provide more specific error messages. The common LookupError subclasses are: IndexError, KeyError, and UnboundLocalError.

IndexError

IndexError is raised when a sequence index is out of range. In Python, sequences include lists, tuples, and strings.

The following example shows a simple IndexError:

list1 = ['apple', 'banana', 'orange', 'grapes']

try:
    fruit = list1[5]
    print(fruit)
except IndexError:
    print("Index out of range.")

Output:

Index out of range.

KeyError

KeyError is raised when a non-existent key is referred to for a dictionary object. It is commonly used when the user requests a non-existent key that is not defined in a dictionary object.

Here is an example of KeyError:

fruits = {'apple': 2, 'banana': 4, 'orange': 1}

try:
    fruit = fruits['mango']
    print(fruit)
except KeyError:
    print("Key does not exist")

Output:

Key does not exist.

UnboundLocalError

UnboundLocalError is raised when a local variable is referenced before it is assigned.

The following example shows UnboundLocalError:

def compute():
    try:
        res = 2 + 3
        print(res)
    except UnboundLocalError:
        print("Local Variable does not exist")
        return

compute()

Output:

5

Conclusion

The LookupError exception is raised whenever the interpreter encounters an error while performing a lookup operation on a dictionary, list, tuple, or set. Python provides many relevant subclasses of LookupError to generate more specific error messages to prevent the misuse of program data. This tutorial provides a comprehensive explanation of the LookupError in Python with examples.

Leave a Reply

Your email address will not be published. Required fields are marked *