‘nonetype’ object is not subscriptable – Python Error


Python throws the error ‘nonetype’ object is not subscriptable, when you assign an array or object to None and then try to access some value using key or index.

This happens due to assignment of array or object to the functions which do not return array but None.

Let’s have a look at this code example –

mySuperHeroList = ["Captain America", "Thor", "Hulk"]
mySuperHeroList = mySuperHeroList.sort()

The problem here is that sort() function sort the actual array and return None. So, mySuperHeroList.sort() will sort the array but return None. And since we are assigning the return value of mySuperHeroList.sort() to mySuperHeroList , so mySuperHeroList became None and we can’t subscript it now.

The correct way of doing it is –

mySuperHeroList = ["Captain America", "Thor", "Hulk"]

Or, you can also use sorted() method which return the sorted array –

mySuperHeroList = ["Captain America", "Thor", "Hulk"]
mySuperHeroList = sorted(mySuperHeroList)

According to Python documentation, these are some of the array functions which do not return anything. So, assigning their result to the array will result in nonetype object not subscriptable error –

  • list.append(x)
  • list.insert(i,x)
  • list.remove(x)
  • list.clear()
  • list.reverse()
  • list.sort()

    Tweet this to help others

Live Demo

Open Live Demo