Python TypeError: NoneType is Not Subscriptable (Fix This Stupid Bug)

Do you encounter the following error message?

TypeError: NoneType is not subscriptable

You’re not alone! This short tutorial will show you why this error occurs, how to fix it, and how to never make the same mistake again.

So, let’s get started!

Summary

Python raises the TypeError: NoneType is not subscriptable if you try to index x[i] or slice x[i:j] a None value. The None type is not indexable, i.e., it doesn’t define the __getitem__() method. You can fix it by removing the indexing or slicing call, or defining the __getitem__ method.

Example

 TypeError: 'NoneType' object is not subscriptable

The following minimal example that leads to the error:

x = None
print(x[0])
# TypeError: 'NoneType' object is not subscriptable

You set the variable to the value None. The value None is not a container object, it doesn’t contain other objects. So, the code really doesn’t make any sense—which result do you expect from the indexing operation?

Exercise: Before I show you how to fix it, try to resolve the error yourself in the following interactive shell:

If you struggle with indexing in Python, have a look at the following articles on the Finxter blog—especially the third!

🌍 Related Articles:

Fixes

You can fix the non-subscriptable TypeError by wrapping the non-indexable values into a container data type such as a list in Python:

x = [None]
print(x[0])
# None

The output now is the value None and the script doesn’t yield an error message anymore.

An alternative is to define the __getitem__() method in your code:

class X:
    def __getitem__(self, i):
        return f"Value {i}"

variable = X()
print(variable[0])
# Value 0

🌍 Related Tutorial: Python __getitem__() magic method

You overwrite the __getitem__ method that takes one (index) argument i (in addition to the obligatory self argument) and returns the i-th value of the “container”.

In our case, we just return a string "Value 0" for the element variable[0] and "Value 10" for the element variable[10].

🌍 Full Guide: Python Fixing This Subsctiptable Error (General)

What’s Next?

I hope you’d be able to fix the bug in your code! Before you go, check out our free Python cheat sheets that’ll teach you the basics in Python in minimal time: