When calling a method in Python, you have to use parentheses (). If you use square brackets [], you will raise the error “TypeError: ‘method’ object is not subscriptable”.
This tutorial will describe in detail what the error means. We will explore an example scenario that raises the error and learn how to solve it.
Table of contents
- TypeError: ‘method’ object is not subscriptable
- Example: Calling A Method With Square Brackets
- Solution
- Summary
TypeError: ‘method’ object is not subscriptable
TypeErrror occurs when you attempt to perform an illegal operation for a particular data type. The part “‘method’ object is not subscriptable” tells us that method is not a subscriptable object. Subscriptable objects have a __getitem__ method, and we can use __getitem__ to retrieve individual items from a collection of objects contained by a subscriptable object. Examples of subscriptable objects are lists, dictionaries and tuples. We use square bracket syntax to access items in a subscriptable object. Because methods are not subscriptable, we cannot use square syntax to access the items in a method or call a method.
Methods are not the only non-subscriptable object. Other common “not subscriptable” errors are:
- “TypeError: ‘float’ object is not subscriptable“,
- “TypeError: ‘int’ object is not subscriptable“
- “TypeError: ‘builtin_function_or_method’ object is not subscriptable“
- “TypeError: ‘function’ object is not subscriptable“
Let’s look at an example of retrieving the first element of a list using the square bracket syntax
pizzas = ["margherita", "pepperoni", "four cheeses", "ham and pineapple"] print(pizzas[0])
The code returns:
margherita
which is the pizza at index position 0. Let’s look at an example of calling a method using square brackets.
Example: Calling A Method With Square Brackets
Let’s create a program that stores fundamental particles as objects. The Particle class will tell us the mass of a particle and its charge. Let’s create a class for particles.
class Particle:
def __init__(self, name, mass):
self.name = name
self.mass = mass
def is_mass(self, compare_mass):
if compare_mass != self.mass:
print(f'The {self.name} mass is not equal to {compare_mass} MeV, it is {self.mass} MeV')
else:
print(f'The {self.name} mass is equal to {compare_mass} MeV')
The Particle class has two methods, one to define the structure of the Particle object and another to check if the mass of the particle is equal to a particular value. This class could be useful for someone studying Physics and particle masses for calculations.
Let’s create a muon object with the Particle class. The mass is in MeV and to one decimal place.
muon = Particle("muon", 105.7)
The muon variable is an object with the name muon and mass value 105.7. Let’s see what happens when we call the is_mass() method with square brackets and input a mass value.
muon.is_mass[105.7]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [18], in <cell line: 1>() ----> 1 muon.is_mass[105.7] TypeError: 'method' object is not subscriptable
We raise the TypeError because of the square brackets used to call the is_mass() method. The square brackets are only suitable for accessing items from a list, a subscriptable object. Methods are not subscriptable; we cannot use square brackets when calling this method.
Solution
We replace the square brackets with the round brackets ().
muon = Particle("muon", 105.7)
Let’s call the is_mass method with the correct brackets.
muon.is_mass(105.7) muon.is_mass(0.51)
The muon mass is equal to 105.7 MeV The muon mass is not equal to 0.51 MeV, it is 105.7 MeV
The code tells us the mass is equal to 105.7 MeV but is not equal to the mass of the electron 0.51 MeV.
To learn more about correct class object instantiation and calling methods in Python go to the article titled “How to Solve Python missing 1 required positional argument: ‘self’“.
Summary
Congratulations on reading to the end of this tutorial! The error “TypeError: ‘method’ object is not subscriptable” occurs when you use square brackets to call a method. Methods are not subscriptable objects and therefore cannot be accessed like a list with square brackets. To solve this error, replace the square brackets with the round brackets after the method’s name when you are calling it.
To learn more about Python for data science and machine learning, go to the online courses page on Python for the best courses available!
Have fun and happy researching!
Welcome to another module of TypeError in the python programming language. In today’s article, we will be discussing an embarrassing Typeerror that usually gets landed up while we are a beginner to python. The error is named as TypeError: ‘method’ object is not subscriptable Solution.
In this guide, we’ll go through the causes and ultimately the solutions for this TypeError problem.
What are Subscriptable Objects in Python?
Subscriptable objects are the objects in which you can use the [item] method using square brackets. For example, to index a list, you can use the list[1] way.
Inside the class, the __getitem__ method is used to overload the object to make them compatible for accessing elements. Currently, this method is already implemented in lists, dictionaries, and tuples. Most importantly, every time this method returns the respective elements from the list.
Now, the problem arises when objects with the __getitem__ method are not overloaded and you try to subscript the object. In such cases, the ‘method’ object is not subscriptable error arises.
Why do you get TypeError: ‘method’ object is not subscriptable Error in python?
In Python, some of the objects can be used to access the inside elements by using square brackets. For example in List, Tuple, and dictionaries. But what happens when you use square brackets to objects which arent supported? It’ll throw an error.
Let us consider the following code snippet:
names = ["Python", "Pool", "Latracal", "Google"]
print(names[0])
int("5")[0]
OUTPUT:- Python TypeError: int object is not subscriptable
This code returns “Python,” the name at the index position 0. We cannot use square brackets to call a function or a method because functions and methods are not subscriptable objects.
Example Code for the TypeError
x = 3 x[0] # example 1 p = True p[0] # example 2 max[2] # example 3
OUTPUT:-
![[Solved] TypeError: ‘method’ Object is not ubscriptable](https://www.pythonpool.com/wp-content/uploads/2021/05/Untitled-1.png)
Explanation of the code
- Here we started by declaring a value x which stores an integer value 3.
- Then we used [0] to subscript the value. But as integer doesn’t support it, an error is raised.
- The same goes for example 2 where p is a boolean.
- In example 3, max is a default inbuilt function which is not subscriptable.
The solution to the TypeError: method Object is not Subscriptable
The only solution for this problem is to avoid using square brackets on unsupported objects. Following example can demonstrate it –
x = 3 print(x) p = True print(p) max([1])
OUTPUT:-
Our code works since we haven’t subscripted unsupported objects.
If you want to access the elements like string, you much convert the objects into a string first. The following example can help you to understand –
x = 3 str(x)[0] # example 1 p = True str(p)[0] # example 2
Also, Read
FAQs
1. When do we get TypeError: ‘builtin_function_or_method’ object is not subscriptable?
Ans:- Let us look as the following code snippet first to understand this.
import numpy as np a = np.array[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
OUTPUT:-

This problem is usually caused by missing the round parentheses in the np.array line.
It should have been written as:
a = np.array([1,2,3,4,5,6,7,8,9,10])
It is quite similar to TypeError: ‘method’ object is not subscriptable the only difference is that here we are using a library numpy so we get TypeError: ‘builtin_function_or_method’ object is not subscriptable.
Conclusion
The “TypeError: ‘method’ object is not subscriptable” error is raised when you use square brackets to call a method inside a class. To solve this error, make sure that you only call methods of a class using round brackets after the name of the method you want to call.
Now you’re ready to solve this common Python error like a professional coder! Till then keep pythoning Geeks!
Arguments in Python methods must be specified within parentheses. This is because functions and methods both use parentheses to tell if they are being called. If you use square brackets to call a method, you’ll encounter an “TypeError: ‘method’ object is not subscriptable” error.
In this guide, we discuss what this error means and why you may encounter it. We walk through an example of this error to help you develop a solution.
Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Access exclusive scholarships and prep courses
Select your interest
First name
Last name
Phone number
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
TypeError: ‘method’ object is not subscriptable
Subscriptable objects are objects with a __getitem__ method. These are data types such as lists, dictionaries, and tuples. The __getitem__ method allows the Python interpreter to retrieve an individual item from a collection.
Not all objects are subscriptable. Methods, for instance, are not. This is because they do not implement the __getitem__ method. This means you cannot use square bracket syntax to access the items in a method or to call a method.
Consider the following code snippet:
cheeses = ["Edam", "Stilton", "English Cheddar", "Parmesan"] print(cheeses[0])
This code returns “Edam”, the cheese at the index position 0. We cannot use square brackets to call a function or a method because functions and methods are not subscriptable objects.
An Example Scenario
Here, we build a program that stores cheeses in objects. The “Cheese” class that we use to define a cheese will have a method that lets us check whether a cheese is from a particular country of origin.
Start by defining a class for our cheeses. We call this class Cheese:
class Cheese:
def __init__(self, name, origin):
self.name = name
self.origin = origin
def get_country(self, to_compare):
if to_compare == self.origin:
print("{} is from {}.".format(self.name, self.origin))
else:
print("{} is not from {}. It is from {}.".format(self.name, to_compare, self.origin))
Our class contains two methods. The first method defines the structure of the Cheese object. The second lets us check whether the country of origin of a cheese is equal to a particular value.
Next, we create an object from our Cheese class:
edam = Cheese("Edam", "Netherlands")
The variable “edam” is an object. The name associated with the cheese is Edam and its country of origin is the Netherlands.
Next, let’s call our get_country() method:
edam.get_country["Germany"]
This code executes the get_country() method from the Cheese class. The get_country() method checks whether the value of “origin” in our “edam” object is equal to “Germany”.
Run our code and see what happens:
Traceback (most recent call last): File "main.py", line 14, in <module> edam.get_country["Germany"] TypeError: 'method' object is not subscriptable
An error occurs in our code.
The Solution
Let’s analyze the line of code that the Python debugger has identified as erroneous:
edam.get_country["Germany"]
In this line of code, we use square brackets to call the get_country() method. This is not acceptable syntax because square brackets are used to access items from a list. Because functions and objects are not subscriptable, we cannot use square brackets to call them.
To solve this error, we must replace the square brackets with curly brackets:
edam.get_country("Germany")
Let’s run our code and see what happens:
Edam is not from Germany. It is from Netherlands.
Our code successfully executes. Let’s try to check whether Edam is from “Netherlands” to make sure our function works in all cases, whether or not the value we specify is equal to the cheese’s origin country:
edam.get_country("Netherlands")
Our code returns:
Edam is from Netherlands.
Our code works if the value we specify is equal to the country of origin of a cheese.
Conclusion
The “TypeError: ‘method’ object is not subscriptable” error is raised when you use square brackets to call a method inside a class. To solve this error, make sure that you only call methods of a class using curly brackets after the name of the method you want to call.
Now you’re ready to solve this common Python error like a professional coder!
![TypeError: builtin_function_or_method object is not subscriptable Python Error [SOLVED]](https://www.freecodecamp.org/news/content/images/size/w2000/2022/11/built_in_not_subable.png)
As the name suggests, the error TypeError: builtin_function_or_method object is not subscriptable is a “typeerror” that occurs when you try to call a built-in function the wrong way.
When a «typeerror» occurs, the program is telling you that you’re mixing up types. That means, for example, you might be concatenating a string with an integer.
In this article, I will show you why the TypeError: builtin_function_or_method object is not subscriptable occurs and how you can fix it.
Every built-in function of Python such as print(), append(), sorted(), max(), and others must be called with parenthesis or round brackets (()).
If you try to use square brackets, Python won’t treat it as a function call. Instead, Python will think you’re trying to access something from a list or string and then throw the error.
For example, the code below throws the error because I was trying to print the value of the variable with square braces in front of the print() function:
And if you surround what you want to print with square brackets even if the item is iterable, you still get the error:
gadgets = ["Mouse", "Monitor", "Laptop"]
print[gadgets[0]]
# Output: Traceback (most recent call last):
# File "built_in_obj_not_subable.py", line 2, in <module>
# print[gadgets[0]]
# TypeError: 'builtin_function_or_method' object is not subscriptable
This issue is not particular to the print() function. If you try to call any other built-in function with square brackets, you also get the error.
In the example below, I tried to call max() with square brackets and I got the error:
numbers = [5, 7, 24, 6, 90]
max_num = max(numbers)
print[max_num]
# Traceback (most recent call last):
# File "built_in_obj_not_subable.py", line 11, in <module>
# print[max_num]
# TypeError: 'builtin_function_or_method' object is not subscriptable
How to Fix the TypeError: builtin_function_or_method object is not subscriptable Error
To fix this error, all you need to do is make sure you use parenthesis to call the function.
You only have to use square brackets if you want to access an item from iterable data such as string, list, or tuple:
gadgets = ["Mouse", "Monitor", "Laptop"]
print(gadgets[0])
# Output: Mouse
numbers = [5, 7, 24, 6, 90]
max_num = max(numbers)
print(max_num)
# Output: 90
Wrapping Up
This article showed you why the TypeError: builtin_function_or_method object is not subscriptable occurs and how to fix it.
Remember that you only need to use square brackets ([]) to access an item from iterable data and you shouldn’t use it to call a function.
If you’re getting this error, you should look in your code for any point at which you are calling a built-in function with square brackets and replace it with parenthesis.
Thanks for reading.
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
In Python, Built-in functions are not subscriptable, if we use the built-in functions as an array to perform operations such as indexing, you will encounter TypeError: ‘builtin_function_or_method’ object is not subscriptable.
This article will look at what TypeError: ‘builtin_function_or_method’ object is not subscriptable error means and how to resolve this error with examples.
If we use the square bracket [] instead of parenthesis() while calling a function, Python will throw TypeError: ‘builtin_function_or_method’ object is not subscriptable.
The functions in Python are called using the parenthesis “()", and that’s how we distinguish the function call from the other operations, such as indexing the list. Usually, when working with lists or arrays, it’s a common mistake that the developer makes.
Let us take a simple example to reproduce this error.
Here in the example below, we have a list of car brands and are adding the new car brand to the list.
We can use the list built-in function to add a new car brand to the list, and when we execute the code, Python will throw TypeError: ‘builtin_function_or_method’ object is not subscriptable.
cars = ['BMW', 'Audi', 'Ferrari', 'Benz']
# append the new car to the list
cars.append["Ford"]
# print the list of new cars
print(cars)
Output
Traceback (most recent call last):
File "c:PersonalIJSCodemain.py", line 4, in <module>
cars.append["Ford"]
TypeError: 'builtin_function_or_method' object is not subscriptable
We are getting this error because we are not correctly using the append() method. We are indexing it as if it is an array (using the square brackets), but in reality, the append() is a built-in function.
How to Fix TypeError: ‘builtin_function_or_method’ object is not subscriptable?
We can fix the above code by treating the append() as a valid function instead of indexing.
In simple terms, we need to replace the square brackets with the parentheses (), making it a proper function.
This happens while working with arrays or lists and using functions like append(), pop(), remove(), etc., and if we perform the indexing operation using the function.
After replacing the code, you can observe that it runs successfully and adds a new brand name as the last element to the list.
cars = ['BMW', 'Audi', 'Ferrari', 'Benz']
# append the new car to the list
cars.append("Ford")
# print the list of new cars
print(cars)
Output
['BMW', 'Audi', 'Ferrari', 'Benz', 'Ford']
Conclusion
The TypeError: ‘builtin_function_or_method’ object is not subscriptable occurs if we use the square brackets instead of parenthesis while calling the function.
The square brackets are mainly used to access elements from an iterable object such as list, array, etc. If we use the square brackets on the function, Python will throw a TypeError.
We can fix the error by using the parenthesis while calling the function.
Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
Sign Up for Our Newsletters
Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.
By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.
В этой строке:
hero.coordinate = hero.step_forward
вы не вызываете метод, а записываете «ссылку» на метод в переменную. При следующей итерации цикла вы пытаетесь сделать hero.coordinate[0] по сути от ссылки на метод, о чем и говорится в ошибке. Вам просто нужно исправить данную строку на
hero.coordinate = hero.step_forward()
А вообще, по логике, метод .step_forward() должен менять координаты объекта, а не возвращать значение. Ваш код и меняет координаты объекта, и возвращает новое значение, которое вы потом еще раз записываете в поле с координатами объекта. Вам в принципе можно просто убрать return в методе step_forward() или никак не использовать значение, возвращенное из step_forward(). Вообще, лучше не менять вручную координаты объекта, обращаясь к ним снаружи, а делать это внутри методов.
Класс лучше реализовать так:
class Hero:
def __init__(self, coordinate)
# Если вы будете использовать один и тот же список с координатами для разных объектов, лучше при инициализации делать копию списка с помощью list
self.coordinate = list(coordinate)
def step_forward(self):
self.coordinate[0] = self.coordinate[0] + 1
Тогда при создании объекта нужно будет еще указывать его координаты.
hero = Hero([0, 0])
enemy_hero = Hero([20, 0])
while True:
distance = sqrt( (enemy_hero.coordinate[0] - hero.coordinate[0])**2 + (enemy_hero.coordinate[1] - hero.coordinate[1])**2)
hero.step_forward()
distance тоже можно сделать методом того же класса:
class Hero:
def __init__(self, coordinate)
self.coordinate = list(coordinate)
def step_forward(self):
self.coordinate[0] = self.coordinate[0] + 1
def distance(self, other):
return sqrt( (other.coordinate[0] - self.coordinate[0])**2 + (other.coordinate[1] - self.coordinate[1])**2)
Тогда цикл будет выглядеть так:
while True:
distance = hero.distance(enemy_hero)
hero.step_forward()
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
Live Demo
This is Akash Mittal, an overall computer scientist. He is in software development from more than 10 years and worked on technologies like ReactJS, React Native, Php, JS, Golang, Java, Android etc. Being a die hard animal lover is the only trait, he is proud of.
Related Tags
- Error,
- python error,
- python-short
Object Is Not Subscriptable
Overview
Example errors:
TypeError: object is not subscriptable
Specific examples:
TypeError: 'type' object is not subscriptableTypeError: 'function' object is not subscriptable
Traceback (most recent call last):
File "afile.py", line , in aMethod
map[value]
TypeError: 'type' object is not subscriptable
This problem is caused by trying to access an object that cannot be indexed as though it can be accessed via an index.
For example, in the above error, the code is trying to access map[value] but map is already a built-in type that doesn’t support accessing indexes.
You would get a similar error if you tried to call print[42], because print is a built-in function.
Initial Steps Overview
-
Check for built-in words in the given line
-
Check for reserved words in the given line
-
Check you are not trying to index a function
Detailed Steps
1) Check for built-in words in the given line
In the above error, we see Python shows the line
This is saying that the part just before [value] can not be subscripted (or indexed). In this particular instance, the problem is that the word map is already a builtin identifier used by Python and it has not been redefined by us to contain a type that subscripts.
You can see a full list of built-in identifiers via the following code:
# Python 3.0
import builtins
dir(builtins)
# For Python 2.0
import __builtin__
dir(__builtin__)
2) Check for instances of the following reserved words
It may also be that you are trying to subscript a keyword that is reserved by Python True, False or None
>>> True[0]
<stdin>:1: SyntaxWarning: 'bool' object is not subscriptable; perhaps you missed a comma?
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'bool' object is not subscriptable
3) Check you are not trying to access elements of a function
Check you are not trying to access an index on a method instead of the results of calling a method.
txt = 'Hello World!'
# Incorrectly getting the first word
>>> txt.split[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'builtin_function_or_method' object is not subscriptable
# The correct way
>>> txt.split()[0]
'Hello'
You will get a similar error for functions/methods you have defined yourself:
def foo():
return ['Hello', 'World']
# Incorrectly getting the first word
>>> foo[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'function' object is not subscriptable
# The correct way
>>> foo()[0]
'Hello'
Solutions List
A) Initialize the value
B) Don’t shadow built-in names
Solutions Detail
A) Initialize the value
Make sure that you are initializing the array before you try to access its index.
map = ['Hello']
print(map[0])
Hello
B) Don’t shadow built-in names
It is generally not a great idea to shadow a language’s built-in names as shown in the above solution as this can confuse others reading your code who expect map to be the builtin map and not your version.
If we hadn’t used an already taken name we would have also got a much more clear error from Python, such as:
>>> foo[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
But don’t just take our word for it: see here
Further Information
- Python 2: Subscriptions
- Python 3: Subscript notation
@Gerry
‘builtin_function_or_method object’ is not subscriptable
This usually happens when a function or any operation is applied against an incorrect object. In such a situation, you are likely to encounter an error called typeerror ‘builtin_function_or_method’ object is not subscriptable. But sometimes, a basic syntax error can cause the error too.
You can fix this error by calling the function properly. In this article, we will get into the details of this Python error.
Example 1
# Python 3 Code
# Declare a variable
myname = 'Stechies'
# Use print() function to print value
print[myname]
Output:
print[myname]
TypeError: 'builtin_function_or_method' object is not subscriptable
Here, the error typeerror ‘builtin_function_or_method’ object is not subscriptableis encountered in the last line. This is because the print() method was not called properly. There are square brackets ”[]” beside print() as it is a list or a tuple. But that is not the case.

The solution to the problems is given below:
print(myname)
The error is removed using this line as print() is called using the parenthesis and not square brackets.
Example 2
# Declare a list
mylist = ["Apple","Banana","Orange"]
# Append a element in the list using append() method
mylist.append['Mango']
print(mylist)
Output:
mylist.append['Mango']
TypeError: 'builtin_function_or_method' object is not subscriptable
Conclusion:
Thus, the best way to avoid encountering such errors is to check whether the syntax is correct. It will save you a lot of time while debugging huge files of code or complicated programs.