You sort a list of scores and try to print the lowest one. Python stops:
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(scores[0])
~~~~~~^^^
TypeError: 'NoneType' object is not subscriptableTypeError: 'NoneType' object is not subscriptable means you used square brackets, like scores[0] or user["age"], on a variable whose value is None. None is Python's "nothing here" value, and you can't take item 0 of nothing. The error is reported on the line with the brackets, but the real mistake is almost always earlier: somewhere, the variable got None when you expected a list or a dictionary. This article shows how to find that place, and the five most common ones.
Try it yourself
Save this as main.py and run python main.py:
scores = [72, 85, 90]
scores = scores.sort()
print(scores[0])You'll get the error above. The fix is in cause 1 below, and it's one word.
What the error means
Read the last line from the left:
TypeError: the problem is the type of a value.'NoneType' object: the value isNone.NoneTypeis the type thatNonebelongs to, the way5belongs toint.is not subscriptable: it can't be used with square brackets. Subscripting is the name forx[0],x["key"]orx[1:3].
So the message really says: the thing before the [ is None. The ^^^ marks show the brackets that failed, and the ~~~~~~ marks under scores show which value was None.
Now ask the question that solves it: where did this variable get its value, and why was that value None?
Cause 1: list methods like sort() and append() return None
This is the most common cause by far. Methods that change a list in place, like sort(), append(), reverse() and extend(), do their work on the list and then return None. So scores = scores.sort() sorts the list and then replaces it with None.
The fix: call the method on its own line, and keep the list:
scores = [72, 85, 90]
scores.sort()
print(scores[0])72If you want a new sorted list and to keep the old one, use the built-in sorted(), which returns the result:
print(sorted([3, 1, 2]))[1, 2, 3]The same trap with append() gives a different message, because the next thing you do is call a method instead of using brackets:
names = ["Sam", "Mia"]
names = names.append("Leo")
names.append("Ava")Traceback (most recent call last):
File "main.py", line 3, in <module>
names.append("Ava")
^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'append'Same cause, same fix: names.append("Leo") on its own line.
Cause 2: a function that doesn't return anything
A function that has no return statement, or reaches its end without one, returns None. A very common version: the function prints the result instead of returning it.
def get_scores():
scores = [72, 85, 90]
print(scores)
result = get_scores()
print(result[0])[72, 85, 90]
Traceback (most recent call last):
File "main.py", line 6, in <module>
print(result[0])
~~~~~~^^^
TypeError: 'NoneType' object is not subscriptableThe list appears on the screen, so it's tempting to think the function "gave" it to you. It didn't: print shows a value, return hands it back. Replace print(scores) with return scores.
Cause 3: a function that returns only sometimes
The sneakier version: the function returns a value in one case and falls off the end in another:
def find_user(name):
users = {"sam": {"age": 31}, "mia": {"age": 27}}
if name in users:
return users[name]
user = find_user("alex")
print(user["age"])Traceback (most recent call last):
File "main.py", line 7, in <module>
print(user["age"])
~~~~^^^^^^^
TypeError: 'NoneType' object is not subscriptableFor "sam" it works. For "alex", the if is false, the function ends without a return, and you get None. That's why this error often appears only for some inputs.
Two good fixes:
- Check before you use it:
user = find_user("alex")
if user is None:
print("No such user")
else:
print(user["age"])- Or make the function always return something useful, such as a default value, or use
users.get(name, {})so the caller always gets a dictionary.
Use is None to check for None, not == None. It's the standard style and always correct.
Cause 4: a search that found nothing
Many functions return None to mean "not found". The classic one is re.search from the regular expression module:
import re
match = re.search(r"\d+", "no digits here")
print(match[0])Traceback (most recent call last):
File "main.py", line 3, in <module>
print(match[0])
~~~~~^^^
TypeError: 'NoneType' object is not subscriptableThere are no digits in the text, so there's no match, and match is None. Always check: if match: print(match[0]). Dictionary .get() behaves the same way: config.get("theme") returns None when the key is missing.
Cause 5: None stored in your data
Sometimes None is a real value in your data, for example a setting that hasn't been chosen yet:
config = {"theme": None}
print(config["theme"]["color"])Traceback (most recent call last):
File "main.py", line 2, in <module>
print(config["theme"]["color"])
~~~~~~~~~~~~~~~^^^^^^^^^
TypeError: 'NoneType' object is not subscriptableThe markers help here: the ~~~ part, config["theme"], is the value that was None, and the ^^^ part, ["color"], is the step that failed. With chained brackets, this tells you exactly which link in the chain broke.
Other errors with None
The same mistake shows up with different words depending on what you tried to do with the None:
TypeError: 'NoneType' object does not support item assignment
TypeError: 'NoneType' object is not iterable
TypeError: object of type 'NoneType' has no len()
AttributeError: 'NoneType' object has no attribute 'append'x[0] = 5onNone: item assignment.for item in xonNone: not iterable.len(x)onNone: has no len().x.append(...)or any method onNone: has no attribute.
All four have the same cause and the same way to find it: trace the variable back to where it became None.
Errors that look alike
TypeError: 'int' object is not subscriptable: the same idea with a number, for exampleage[0]whenageis31. You can't take an item of a single number.TypeError: 'function' object is not subscriptable: you used brackets on a function name instead of calling it:get_scores[0]instead ofget_scores()[0].TypeError: unsupported operand type(s): the value exists but has the wrong type for+or-. See unsupported operand: 'int' and 'str'.NameError: name is not defined: the variable doesn't exist at all, which is different from existing with the valueNone. See NameError: name is not defined.
Wrong fixes that don't help
- Wrapping the line in
try/except TypeError. It hides the symptom. The variable is stillNone, and the next line that uses it fails. - Setting the variable to
[]right before the line. The error goes away, and so does your data. - Changing
[0]to.get(0).Nonehas no.geteither: you'd get thehas no attributeversion.
A debugging walkthrough
A program reads orders and fails with 'NoneType' object is not subscriptable on print(order["total"]). Here's the order to check:
- Find the variable before the brackets:
order. - Find where it got its value. Search for
order =in the file. - If it comes from a function, open the function. Does every path end with
return? Does it print instead of return? - If it comes from a method, check whether the method changes things in place (
sort,append,update) and returnsNone. - If it comes from a search or
.get(), ask whether "not found" is possible, and add anif ... is Nonecheck. - Print the value right after it's assigned:
print(repr(order)). If it showsNone, you've found the line.
Practice
Predict the output, or the error, before you run each one.
x = [3, 1, 2].sort(), thenprint(x).d = {"a": 1}, thenprint(d.get("b")["c"]).names = ["Sam"], thennames.reverse(), thenprint(names[0]).
Answers. (1) It prints None, with no error, because print can show None. (2) 'NoneType' object is not subscriptable: d.get("b") is None. (3) No error: prints Sam. reverse() returned None, but the result wasn't assigned to names, so the list is fine.
Frequently asked questions
What does "'NoneType' object is not subscriptable" mean?
You used square brackets on a variable whose value is None. Find where that variable was set, and why it got None instead of a list or dictionary.
Why does list.sort() return None?
Because it sorts the list in place, and Python's convention is that methods which change an object return None. Use sorted(my_list) if you want a new list back.
How do I check if a variable is None?
if x is None:. Use is, not ==.
Why does my function return None?
It has no return statement, or one of its paths reaches the end without one. A print inside the function shows a value but doesn't return it.
Is this the same error in Python 3.8?
Yes. The message is the same in older versions. Newer versions add the ~~~ and ^^^ marks under the line, which show which part was None.
A quick checklist
- Look at the variable right before the
[: it'sNone. - Find the line that assigned it.
- Was it
x = x.sort()orx = x.append(...)? Call the method on its own line. - Was it a function? Make sure every path returns a value.
- Was it a search or
.get()? Check forNonebefore using the result.
For a method that works on every error, read how to read an error message. The Python documentation explains the None constant and why list.sort() returns it.
