Register Login

TypeError: 'NoneType' object is not subscriptable

Updated Dec 12, 2019

In python, objects which implement the __getitem__ method known as a subscriptable object. 

In simple words, we can say it describes objects that are “containers” which contains other objects. Its includes lists, tuples, and dictionaries.

This error occurs when you try to subscript an object having “none” value.

TypeError: 'NoneType' object is not subscriptable

Example:

mylist=None
print(mylist[0])

Output:

TypeError: 'NoneType' object is not subscriptable

In the above example we are trying to print the value of “NoneType” object at index [0].

If we print the data type of "mylist" variable, it returns 'NoneType' variable. As shown below.

print(type(mylist)) # <class 'NoneType'>

Example with function returning "none":

def myfun(x,y):
    print('Sum: ',x+y)

mysum = myfun(20,30)

print('Sum: ',mysum[0])

Output:

Sum:  50
Traceback (most recent call last):
  File "subscriptable.py", line 6, in <module>
    print('Sum: ',mysum[0])
TypeError: 'NoneType' object is not subscriptable

In the above example, function “myfun” is not returning any value, but printing the output, So we are trying to take the value in “mysum” variable and printing the value at index “mysum[0]” which is “None”.

As we know that if a function not returning any value which means it returns “NoneType”.

If we print the data type of "mysum" variable, it returns 'NoneType' variable. As shown below.

print(type(mysum)) # <class 'NoneType'>​​​​​​​

Example:

my_var = [1,2,3,5,6,7]
my_rev = my_var.reverse()
print('Item at list 0',my_rev[0])

Output:

Traceback (most recent call last):
  File "subscriptable.py", line 3, in <module>
    print('Item at list 0',my_rev[0])
TypeError: 'NoneType' object is not subscriptable

In the above example we are trying to take a output of reverse() method in my_rev variable, but  as we know reverse() method does not return any value but reverse the list in place.

So the value stored in variable “my_rev” is NoneType. 

If we print the data type of "my_rev" variable, it returns 'NoneType' variable. As shown below.

print(type(my_rev)) # <class 'NoneType'>

Correct Example:

my_var = [1,2,3,5,6,7]
my_var.reverse()
print('Item at list [0]:',my_var[0])

Output:

Item at list [0]: 7


×