‘method’ object is not subscriptable – Python Error

Total
0
Shares

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

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like

Python check if list is empty

Table of Contents Hide Using notUsing len()Using == []Live DemoRelated Posts: To check if list is empty in Python, you can use multiple methods like – if not list_var: or…
View Post

How to rename columns in Pandas Python?

Table of Contents Hide 1. Assigning new columns to attribute .columns2. Making columns copy, change required one and reassign3. Using rename() function4. Using set_axis() function5. Using lambda functionLive DemoRelated Posts:…
View Post