Ecoturtle
Ecoturtle

Reputation: 455

'method' object is not subscriptable. Don't know what's wrong

I'm writing some code to create an unsorted list but whenever I try to insert a list using the insert method I get the 'method' object is not subscriptable error. Not sure how to fix it. Thanks.

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


myList = UnsortedList()
myList.insert[1, 2, 3]

Upvotes: 31

Views: 206163

Answers (2)

Malik Hamza
Malik Hamza

Reputation: 350

Try this:

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


 myList = UnsortedList()
 myList.insert([1, 2, 3])

This will work. While making object of class your forgot to put parenthesis.

Upvotes: 2

zondo
zondo

Reputation: 20336

You need to use parentheses: myList.insert([1, 2, 3]). When you leave out the parentheses, python thinks you are trying to access myList.insert at position 1, 2, 3, because that's what brackets are used for when they are right next to a variable.

Upvotes: 59

Related Questions