KeyError vs IndexError in Python Explained

KeyError and IndexError both happen when your code tries to access something that is not available.

The difference is simple:

  • KeyError is about a missing dictionary key
  • IndexError is about a list or tuple position that does not exist

If you can quickly tell whether you are working with a dictionary or a sequence like a list, you can usually fix the problem fast.

Quick fix #

data = {"name": "Ana"}
items = [10, 20, 30]

# KeyError fix: check the key first or use get()
print(data.get("age"))  # None

# IndexError fix: check the index first
index = 5
if 0 <= index < len(items):
    print(items[index])
else:
    print("Index out of range")

Use dict.get() for possibly missing dictionary keys. Check the length before using a list or tuple index.

What is the difference between KeyError and IndexError? #

  • KeyError happens when you ask a dictionary for a key that does not exist.
  • IndexError happens when you ask a list or tuple for a position that does not exist.
  • A key is a dictionary label like "name".
  • An index is a numeric position like 0, 1, 2.

For example:

  • user["email"] uses a key
  • items[2] uses an index

If you need a refresher, see Python dictionaries explained and Python lists explained.

When KeyError happens #

KeyError is most common with dictionaries.

It happens when code like this tries to read a missing key:

user = {"name": "Ana"}
print(user["email"])

The dictionary exists, but "email" is not inside it.

Common causes:

  • Misspelled keys
  • Unexpected input data
  • Assuming JSON or API data always contains the same fields
  • Using the wrong object type

If you want a full guide, see KeyError in Python: causes and fixes.

When IndexError happens #

IndexError is most common with lists and tuples.

It happens when code tries to access a position outside the valid range:

items = [10, 20, 30]
print(items[5])

The list exists, but index 5 is too large.

Common causes:

  • Loops that go too far
  • Hard-coded indexes
  • Empty lists
  • Assuming a list always has enough items

For a deeper explanation, see IndexError in Python: causes and fixes.

Example: KeyError #

Here is a simple example that causes KeyError:

user = {"name": "Ana", "city": "Lima"}
print(user["email"])

Output:

KeyError: 'email'

Why it happens:

  • user is a dictionary
  • The code asks for the key "email"
  • That key is missing

Fix 1: Use get() #

user = {"name": "Ana", "city": "Lima"}
print(user.get("email"))

Output:

None

get() returns None instead of raising an error if the key is missing.

You can also give a default value:

user = {"name": "Ana", "city": "Lima"}
print(user.get("email", "No email found"))

Output:

No email found

See Python dictionary get() method for more examples.

Fix 2: Check the key first #

user = {"name": "Ana", "city": "Lima"}

if "email" in user:
    print(user["email"])
else:
    print("Key not found")

Fix 3: Add the missing key #

user = {"name": "Ana", "city": "Lima"}
user["email"] = "ana@example.com"

print(user["email"])

Example: IndexError #

Here is a simple example that causes IndexError:

items = [10, 20, 30]
print(items[5])

Output:

IndexError: list index out of range

Why it happens:

  • items is a list
  • Valid indexes are 0, 1, and 2
  • Index 5 does not exist

Fix 1: Check the index before using it #

items = [10, 20, 30]
index = 5

if 0 <= index < len(items):
    print(items[index])
else:
    print("Index out of range")

Fix 2: Change loop logic #

Bad example:

items = [10, 20, 30]

for i in range(5):
    print(items[i])

This fails because the loop tries indexes that do not exist.

Better:

items = [10, 20, 30]

for i in range(len(items)):
    print(items[i])

Best for beginners:

items = [10, 20, 30]

for item in items:
    print(item)

Looping directly over the list avoids many index mistakes.

If needed, review the len() function explained.

How to choose the right fix #

When you see the error, first look at the object you are accessing.

  • If the code uses square brackets on a dictionary, check the key
  • If the code uses square brackets on a list or tuple, check the position
  • Print the object to confirm what it contains
  • Use type() if you are not sure what kind of object you have

Example:

data = {"name": "Ana"}
items = [10, 20, 30]

print(type(data))
print(type(items))

Output:

<class 'dict'>
<class 'list'>

A good rule:

  • Dictionary + missing label = KeyError
  • List or tuple + bad numeric position = IndexError

Beginner debugging steps #

If you are not sure what is wrong, use these steps:

  1. Read the last line of the traceback first
  2. Find the variable being accessed
  3. Check whether it is a dictionary, list, or tuple
  4. Inspect the available keys or valid indexes
  5. Check for empty data structures

Useful debugging commands:

print(type(data))
print(data)
print(data.keys())

print(len(items))
print(index)
print(list(enumerate(items)))

What these help you see:

  • print(type(data)) shows the object type
  • print(data) shows the current contents
  • print(data.keys()) shows dictionary keys
  • print(len(items)) shows how many items are in the list
  • print(index) shows the index you are trying to use
  • print(list(enumerate(items))) shows each item with its index

Common causes beginners mix up #

These mistakes often cause confusion:

  • Treating a dictionary like a list
  • Treating a list like a dictionary
  • Assuming API or JSON data always contains the same keys
  • Assuming a list always has enough items

Other common causes:

  • Using data["missing_key"] on a dictionary
  • Misspelling a dictionary key
  • Expecting JSON data to contain a key that is not present
  • Using list[index] with an index larger than len(list) - 1
  • Accessing index 0 on an empty list
  • Using the wrong data type for the operation

Quick comparison table #

ErrorUsually happens withWhat is missingExampleCommon fix
KeyErrorDictionaryKeyuser["email"]Use get() or check if key in dict
IndexErrorList or tupleValid positionitems[5]Check bounds with len()

Another quick way to remember it:

  • KeyError uses labels like "name"
  • IndexError uses positions like 0 or 3

FAQ #

Is KeyError only for dictionaries? #

Mostly yes for beginner use. It usually appears when a dictionary key is missing.

Does IndexError happen with dictionaries? #

No. IndexError is for sequences like lists and tuples, not dictionary keys.

Should I use get() to avoid KeyError? #

Yes, if a missing key is acceptable. get() returns a default value instead of raising KeyError.

If you want examples, see how to check if a key exists in a dictionary in Python.

How do I avoid IndexError in a loop? #

Loop directly over the list when possible, or make sure the index stays below len(list).

See also #

Press Esc to close