What does TypeError: 'NoneType' object is not subscriptable mean?
What the error means
In Python, subscriptable objects are those that implement __getitem__(), such as lists, dictionaries, strings, and tuples. NoneType (the type of None) does not implement this, so using square brackets on None raises TypeError: 'NoneType' object is not subscriptable.
This typically happens when a function returns None instead of the expected list or dictionary, or when you forget to initialize a variable.
How to fix it
Find the variable that is None. The traceback will show the line with the subscript operation. Check why that variable is None — perhaps a function didn't return a value, or a method like .get() returned None.
Ensure the variable is assigned a proper container before subscripting. If a function might return None, check its return value or provide a default.
- Check that functions return a value (not just print or modify in place).
- Use dict.get(key, default) instead of dict[key] to avoid KeyError, but note that get returns None if no default is given.
- Initialize variables to empty lists or dictionaries instead of None.
- Use if x is not None: before subscripting.
- If using an API that returns None on failure, handle that case explicitly.
Example
Suppose you have: result = some_function() and then print(result[0]). If some_function() returns None (because it has no return statement), you'll get this error. Fix by adding return [] or return [1,2,3] to the function, or by checking result before subscripting.
Common mistakes
- Thinking None is the same as an empty list — it's not; you can't index None.
- Assuming a function returns a list when it actually returns None by default.
- Using dict.get() without a default and then subscripting the result, which can be None.
