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()
print(mySuperHeroList[0])

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"]
mySuperHeroList.sort()
print(mySuperHeroList[0])

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

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

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

Demo might not work in private window (incognito)

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles