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:
KeyErroris about a missing dictionary keyIndexErroris 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?
KeyErrorhappens when you ask a dictionary for a key that does not exist.IndexErrorhappens 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 keyitems[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:
useris 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:
itemsis a list- Valid indexes are
0,1, and2 - Index
5does 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:
- Read the last line of the traceback first
- Find the variable being accessed
- Check whether it is a dictionary, list, or tuple
- Inspect the available keys or valid indexes
- 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 typeprint(data)shows the current contentsprint(data.keys())shows dictionary keysprint(len(items))shows how many items are in the listprint(index)shows the index you are trying to useprint(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 thanlen(list) - 1 - Accessing index
0on an empty list - Using the wrong data type for the operation
Quick comparison table
| Error | Usually happens with | What is missing | Example | Common fix |
|---|---|---|---|---|
KeyError | Dictionary | Key | user["email"] | Use get() or check if key in dict |
IndexError | List or tuple | Valid position | items[5] | Check bounds with len() |
Another quick way to remember it:
KeyErroruses labels like"name"IndexErroruses positions like0or3
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).