One error you might encounter when running Python code is:
TypeError: 'NoneType' object is not subscriptable
This error occurs when you attempt to access an element of a
None object as if it were a subscriptable object (like a string, list, or set) using the square brackets
Most likely, you’ve mistaken a
None object for an iterable because you assign the result of calling iterable methods such as the
This tutorial will show you an example that causes this error and how I fix it in practice.
How to reproduce this error
Suppose you have a list of strings in your code, which you sorted using the
my_list = ["z", "b", "k"] sorted_list = my_list.sort()
Next, you want to access an element of the
sorted_list as follows:
But you get this error:
Traceback (most recent call last): File "main.py", line 3, in <module> print(sorted_list) ~~~~~~~~~~~^^^ TypeError: 'NoneType' object is not subscriptable
This error occurs because the
list.sort() method in Python sorts the list in place, meaning the original list is changed without returning a new sorted list.
You can test this by printing the
my_list = ["z", "b", "k"] sorted_list = my_list.sort() print(my_list) print(sorted_list)
['b', 'k', 'z'] None
As you can see, the
my_list variable is already ordered, while the
sorted_list variable contains a
How to fix this error
To resolve this error, you need to access the sorted list items directly in the original list.
You don’t need to assign a new variable when calling the
sort() method because the method doesn’t return any value:
my_list = ["z", "b", "k"] my_list.sort() print(my_list) # k
When in doubt, you need to check on the variable you accessed using the subscript (square brackets) notation.
You might expect the variable to be a different type, but you got a
None instead. Trace the code and see where the variable is assigned a
None in your source code.
TypeError: 'NoneType' object is not subscriptable occurs when you attempt to access a
None object using the square brackets
The square brackets are reserved for subscriptable objects such as a string, a list, or a tuple, so using it on a
None object will raise an error.
To resolve this error, you need to make sure you’re not accessing a
None object using square brackets.
I hope this tutorial is useful. See you in other tutorials! 👋