KeyError and IndexError (Python)
In short: A key is missing from the dictionary (KeyError) or a list index lies outside the list (IndexError).
In more detail: Both errors arise when accessing elements that do not exist. They are cousins of Java’s ArrayIndexOutOfBoundsException.
In Depth
KeyError
age = {"Mia": 17}
print(age["Tom"]) # KeyError: 'Tom'The key "Tom" is not in the dictionary. Typos and capitalisation count too. Solutions:
age.get("Tom")returnsNone,age.get("Tom", 0)a default value.- Check beforehand:
if "Tom" in age:. - Use
collections.defaultdictorsetdefault. - With JSON data print the actual keys (
print(data.keys())).
IndexError
numbers = [10, 20, 30]
print(numbers[3]) # IndexError: list index out of rangeValid indices are 0 to len(list) - 1. Frequent: off-by-one in loops (range(len(x)+1)), empty lists, wrong index after deleting elements. Solutions:
- Check
if i < len(numbers):orif numbers:for “not empty”. - Iterate with
for n in numbers:instead of indices. - Negative indices count from the end:
numbers[-1]. - Use
try/except IndexErroronly where absence is expectable.
Troubleshooting
Read the line number in the traceback, print len() or the keys before that line and check whether the data really looks as you think (empty response, different structure, None). The debugger or print at the right place saves a lot of time.
See also: ArrayIndexOutOfBoundsException, TypeError, ModuleNotFoundError