RuntimePython Error

LookupError

LookupError

Traceback

terminal
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    return container[key]  # may raise IndexError or KeyError
LookupError

What causes this error

An index or key lookup failed. This is the base class for IndexError and KeyError and is not usually raised directly.

How to fix it

Catch LookupError when you want to handle both IndexError and KeyError. Use `.get()` for dicts and bounds checking for sequences. Prefer specific exception types when you know the data structure.

Code that causes this error

Broken
def get_item(container, key):
    return container[key]  # may raise IndexError or KeyError

Fixed code

Fixed
def get_item(container, key, default=None):
    try:
        return container[key]
    except LookupError:
        return default

About LookupError

LookupError is the base class for exceptions raised when a key or index is invalid. It is the parent of both KeyError and IndexError. You typically do not see LookupError raised directly — instead, you encounter its subclasses.

However, catching LookupError in an except clause is useful when you want to handle both KeyError and IndexError with the same code. This is particularly handy in generic code that works with both sequences and mappings, where you want to catch any failed lookup regardless of the container type. Some third-party libraries and ORMs also raise LookupError subclasses for not-found conditions.

The LookupError class itself is primarily an organizational hierarchy marker in Python's exception taxonomy.

Common scenarios

1

Infinite recursion from missing or incorrect base cases

2

Modifying dictionaries or sets during iteration

3

Calling generators or coroutines in unsupported ways

4

Using asyncio event loops incorrectly or attempting to nest them

Related errors