TypeError: 'NoneType' object is not subscriptable
What it means
You used square brackets on None. None is the value Python uses for "nothing", and it has no items to pick. Usually a function or method gave you None where you expected a list, string or dictionary.
1. Saving the result of `.sort()`
This raises the error
Broken
scores = [72, 95, 88]
ranked = scores.sort(reverse=True)
print("Top score:", ranked[0])
Output
Traceback (most recent call last): File "<exec>", line 3, in <module> TypeError: 'NoneType' object is not subscriptable
The fix
Fixed
scores = [72, 95, 88]
ranked = sorted(scores, reverse=True)
print("Top score:", ranked[0])
Output
Top score: 95
list.sort() sorts the list in place and returns None. sorted() returns a new sorted list you can index. .append(), .reverse() and .insert() also return None.
2. A function that forgets to `return`
This raises the error
Broken
def get_names():
names = ["Ada", "Alan", "Grace"]
names = get_names()
print(names[0])
Output
Traceback (most recent call last): File "<exec>", line 5, in <module> TypeError: 'NoneType' object is not subscriptable
The fix
Fixed
def get_names():
names = ["Ada", "Alan", "Grace"]
return names
names = get_names()
print(names[0])
Output
Ada
A function with no return gives back None. Return the value you want to use outside it.
3. A lookup that found nothing
This raises the error
Broken
users = {"ada": {"age": 36}}
user = users.get("alan")
print(user["age"])
Output
Traceback (most recent call last): File "<exec>", line 3, in <module> TypeError: 'NoneType' object is not subscriptable
The fix
Fixed
users = {"ada": {"age": 36}}
user = users.get("alan")
if user is None:
print("No such user")
else:
print(user["age"])
Output
No such user
dict.get() returns None when the key is missing, and so does re.match() when the pattern does not match. Check for None before indexing.
When you see this error, check
- Print the variable just before the failing line. If it shows
None, find the line that assigned it. - Do not save the result of in-place methods such as
.sort(),.append(),.reverse()and.update(). - Make sure every path through your function ends in a
returnwith a value. - Guard values that can be missing with
if value is not None:.
Related errors
All Python errors · How to read a traceback · Step through your code