TypeError: ‘method’ object is not subscriptable in Python

In Python, some objects like lists, tuples, and dictionaries, strings are known as subscriptable objects. These subscriptable objects easily access their element using the square bracket instead of parentheses.

The “TypeError: method object is not subscriptable” is invoked in the Python program when the user tries to access the method or function using the square bracket.

This write-up will give you various reasons and solutions for the error “method object is not subscriptable” in Python using the following points:

So, let’s get started!

Reason 1: Calling Method Using Square Bracket

The primary reason for this error is using square brackets instead of parentheses to access the method. The sample example error is shown in the following snippet:

The above snippet shows that the error is invoked in the program when the “random.randint()” method is accessed using the square bracket.

Solution: Use Parentheses

To fix this error, use the parentheses to access the “random.randint()” method. The example code below shows the correct way of accessing the method in Python:

Code:

import random
output = random.randint(0,20)
print(output)

In the above code, the random module is imported, and the list is initialized in the program. The “random.randint()” accepts the starting and ending range of numbers inside the parentheses and returns the random numbers within the given range.

Output:

The above output shows a random value generated by the function “random.randint()”.

Reason 2: Accessing the Class Method

The “TypeError: method object is not subscriptable” also occurs in Python programs when the user tries to call the user-defined classes method using the square bracket instead of parentheses. An example of this error is shown in the below snippet:

The above output displays “TypeError”, which arises due to incorrect accessing of the class’s method named “name”.

Solution: Use Parentheses

To fix this error, we use parentheses instead of square brackets to access methods in the Python program:

Code:

class students():
    def name(self, name):
        return name
   
std = students()
output = std.name('Lily')
print(output)

In the above code, the class named “students” is defined in the program. The “name()” method is defined inside the class using the def keyword. While at the time of accessing the “name()” method is accessed using the parentheses instead of the square bracket.

Output:

The above output shows the value of the “name()” method of the user-defined class.

Conclusion

The “TypeError: method object is not subscriptable” occurs in Python when a user tries to call the method using a square bracket or attempts to access a class method incorrectly. To resolve this error, use parentheses instead of square brackets while accessing the method in the program. This article has presented various reasons and solutions for “TypeError: method object is not subscriptable” in Python.