‘method’ object is not subscriptable – Python Error

Python throws error, ‘method’ object is not subscriptable, when a class method is indexed or subscripted using square brackets [] like if its a list or tuple or array.

Consider this example –

class SuperHeroList:
    def __init__(self):
        self.theSuperHeroList = list()
    def __getitem__(self, i):
       print(self.theSuperHeroList[i])
    def insert(self, lst):
        for x in lst:
            try:
                self.theSuperHeroList.append(str(x))
            except:
                print("oops")


myList = SuperHeroList()
myList.insert["Captain America", "Hulk", "Thor"]

This code will throw the error that method is not subscriptable. In our SuperHeroList class we have defined a method insert(), which is accepting a list as argument and appending it with internal list, theSuperHeroList.

Later in the code, we are instantiating an object of the class and calling insert method over that object – myList.insert["Captain America", "Hulk", "Thor"]. The problem lies here.

insert is a method and should be called with parenthesis () and not with square brackets []. The correct way of doing it is –

myList.insert(["Captain America", "Hulk", "Thor"])

So, our above code will change to –

class SuperHeroList:
    def __init__(self):
        self.theSuperHeroList = list()
    def __getitem__(self, i):
       print(self.theSuperHeroList[i])
    def insert(self, lst):
        for x in lst:
            try:
                self.theSuperHeroList.append(str(x))
            except:
                print("oops")


myList = SuperHeroList()
myList.insert(["Captain America", "Hulk", "Thor"])
myList[1]

# Output: Hulk

    Tweet this to help others