Меню

Builtin function or method python ошибка

Can’t believe this thread was going on for so long.
You would get this error if you got distracted
and used [] instead of (), at least my case.

Pop is a method on the list data type,
https://docs.python.org/2/tutorial/datastructures.html#more-on-lists

Therefore, you shouldn’t be using pop as if it was a list itself, pop[0].
It’s a method that takes an optional parameter representing an index,
so as Tushar Palawat pointed out in one of the answers that didn’t get approved,
the correct adjustment which will fix the example above is:

listb.pop(0)

If you don’t believe, run a sample such as:

if __name__ == '__main__':
  listb = ["-test"]
  if( listb[0] == "-test"):
    print(listb.pop(0))

Other adjustments would work as well, but it feels as they are abusing the Python language. This thread needs to get fixed, not to confuse users.

Addition,
a.pop() removes and returns the last item in the list.
As a result, a.pop()[0] will get the first character of that
last element. It doesn’t seem that is what the given code snippet
is aiming to achieve.

TypeError: builtin_function_or_method object is not subscriptable Python Error [SOLVED]

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

Functions are blocks of code that work and behave together under a name. Built-in functions have their functionality predefined. To call a built-in function, you need to use parentheses (). If you do not use parentheses, the Python interpreter cannot distinguish function calls from other operations such as indexing on a list object.

Using square brackets instead of parentheses to call a built-in function will raise the “TypeError: ‘builtin_function_or_method’ object is not subscriptable”.

In this tutorial, we will go into detail on the error definition. We will go through an example scenario of raising the error and how to solve it.


Table of contents

  • TypeError: ‘builtin_function_or_method’ object is not subscriptable
  • Example: Using the Built-in sum Function with Square Brackets
    • Solution
  • Summary

TypeError: ‘builtin_function_or_method’ object is not subscriptable

Two parts of the error tell you what has gone wrong. TypeError occurs whenever we try to perform an illegal operation for a specific data type. For example, trying to iterate over a non-iterable object, like an integer will raise the error: “TypeError: ‘int’ object is not iterable“.

The part “‘builtin_function_or_method’ object is not subscriptable” occurs when we try to access the elements of a built-in function, which is not possible because it is a non-subscriptable object. Accessing elements is only suitable for subscriptable objects like strings, lists, dictionaries, and tuples. Subscriptable objects implement the __getitem__() method, non-subscriptable objects do not implement the __getitem__() method.

Let’s look at the correct use of indexing on a string:

string = "Machine Learning"

print(string[0])

Example: Using the Built-in sum Function with Square Brackets

Let’s write a program that defines an array of integers and a variable that stores the sum of the integers in the array. The sum() function calculates the sum of Python container objects, including lists, tuples and dictionaries.

numbers = [10, 4, 2, 5, 7]

total = sum[numbers]

print(total)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
total = sum[numbers]

TypeError: 'builtin_function_or_method' object is not subscriptable

In this code, we are trying to sum the integers in the array called numbers, but we are using square brackets [] instead of parenthesis (), which tells the Python interpreter to treat sum like a subscriptable object. But indexing is illegal for built-in functions because they are not containers of objects.

Solution

To solve the problem, we replace the square brackets with parentheses after the function name:

numbers = [10, 4, 2, 5, 7]

total = sum(numbers)

print(total)
28

Our code successfully calculated the sum of the integers in the array and printed the sum value to the console.

Summary

Congratulations on reading to the end of this tutorial.

For further reading on not subscriptable errors, go to the articles:

  • How to Solve Python TypeError: ‘method’ object is not subscriptable
  • How to Solve Python TypeError: ‘Response’ object is not subscriptable

Go to the online courses Python page to learn more about Python for data science and machine learning.

Have fun and happy researching!

To call a built-in function, you need to use parentheses. Parentheses distinguish function calls from other operations that can be performed on some objects, like indexing.

If you try to use square brackets to call a built-in function, you’ll encounter the “TypeError: ‘builtin_function_or_method’ object is not subscriptable” error. 

Get offers and scholarships from top coding schools illustration

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

Email

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.

In this guide, we talk about what this error means and why you may encounter it. We’ll walk through an example so that you can figure out how to solve the error.

TypeError: ‘builtin_function_or_method’ object is not subscriptable

Only iterable objects are subscriptable. Examples of iterable objects include lists, strings, and dictionaries. Individual values in these objects can be accessed using indexing. This is because items within an iterable object have index values.

Consider the following code:

languages = ["English", "French"]
print(languages[0])

Our code returns “English”. Our code retrieves the first item in our list, which is the item at index position 0. Our list is subscriptable so we can access it using square brackets.

Built-in functions are not subscriptable. This is because they do not return a list of objects that can be accessed using indexing.

The “TypeError: ‘builtin_function_or_method’ object is not subscriptable” error occurs when you try to access a built-in function using square brackets. This is because when the Python interpreter sees square brackets it tries to access items from a value as if that value is iterable.

An Example Scenario

We’re going to build a program that appends all of the records from a list of homeware goods to another list. An item should only be added to the next list if that item is in stock.

Start by defining a list of homeware goods and a list to store those that are in stock:

homewares = [
	{ "name": "Gray Lampshade", "in_stock": True },
	{ "name": "Black Wardrobe", "in_stock": True },
{ "name": "Black Bedside Cabinet", "in_stock": False }
]
in_stock = []

The “in_stock” list is presently empty. This is because we have not yet calculated which items in stock should be added to the list.

Next, we use a for loop to find items in the “homewares” list that are in stock. We’ll add those items to the “in_stock” list:

for h in homewares:
	if h["in_stock"] == True:
		in_stock.append[h]

print(in_stock)

We use the append() method to add a record to the “in_stock” list if that item is in stock. Otherwise, our program does not add a record to the “in_stock” list. Our program then prints out all of the objects in the “in_stock” list.

Let’s run our code and see what happens:

Traceback (most recent call last):
  File "main.py", line 10, in <module>
	in_stock.append[h]
TypeError: 'builtin_function_or_method' object is not subscriptable

Our code returns an error.

The Solution

Take a look at the line of code that Python points to in the error:

We’ve tried to use indexing syntax to add an item to our “in_stock” list variable. This is incorrect because functions are not iterable objects. To call a function, we need to use parenthesis.

We fix this problem by replacing the square brackets with parentheses:

Let’s run our code:

[{'name': 'Gray Lampshade', 'in_stock': True}, {'name': 'Black Wardrobe', 'in_stock': True}]

Our code successfully calculates the items in stock. Those items are added to the “in_stock” list which is printed to the console.

Conclusion

The “TypeError: ‘builtin_function_or_method’ object is not subscriptable” error is raised when you try to use square brackets to call a function.

This error is raised because Python interprets square brackets as a way of accessing items from an iterable object. Functions must be called using parenthesis. To fix this problem, make sure you call a function using parenthesis.

Now you’re ready to solve this common Python error like an expert!

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.

Avatar Of Srinivas Ramakrishna

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.

Python provides many built-in functions and methods, such as

sum()

,

upper()

,

append()

,

float()

,

int()

, etc. And some of these functions or methods accept arguments, and some do not.

To call or use a built-in function, we write its name followed by the parenthesis. For example

float()

. But if we use square brackets

[]

instead of parenthesis, we get the

TypeError: ‘builtin_function_or_method’ object is not subscriptable

error in Python.

In this Python guide, we will walk through this error and learn what this error occurs and how to solve it. We will also discuss some examples to have a better understanding of this error.

This error statement is divided into two parts

Error Type

and

Error Message

.

  1. Error Type (


    TypeError


    ): TypeError raises in Python when we try to call a function or use an operation with some incorrect type.
  2. Error Message (


    ‘builtin_function_or_method’ object is not subscriptable


    ): This is the actual error message, which is telling us that we are using the square brackets

    []

    to call the function or method instead of parenthesis

    ()

    .


The Error Reason

In Python, those objects which use indexing and keys to access their elements are known as subscriptable objects. Python string, list, dictionary, and tuples are examples of subscriptable objects.

To access the elements from subscriptable objects, we write the object variable name followed by the square brackets

[]

and the element’s index or key-value inside the bracket. For instance

>>> string = "Hello World"
>>> string[0]
'H'

But Python inbuilt functions are not subscriptable objects, and when we use the square bracket after the inbuilt function or method name, we receive the

TypeError: 'builtin_function_or_method' object is not subscriptable

error.


Example

Let’s use the square bracket

[]

on the built-in Python function

sum

that is used to calculate the sum of Python container objects like lists, tuples, and dictionaries.

bill = [1,2,3,4,5]

# error (using a square bracket to call a function)
total = sum[bill]

print(total)


Output

Traceback (most recent call last):
File "main.py", line 4, in <module>
total = sum[bill]
TypeError: 'builtin_function_or_method' object is not subscriptable


Break the Code

If we look at the error statement provided by Python, we can see that we are receiving the error at line 4. Where we are trying to compute the total sum of our

bill

list object using the Python in-built function

sum

. But in line 4, to call the

sum

function, we have used the square bracket

[]

instead of

()

parenthesis, that’s why Python threw that error because Python misunderstood the function as a subscriptable object.


Solution

The solution to the problem is very simple, whenever you see the

'builtin_function_or_method' object is not subscriptable

error in your Python program, all you need to do is visit the error line code that the Python output error statement is showing and replace the mistyped

[]

bracket after the function with the parenthesis

()

.


Solution Example

Now let’s debug the above example where we are getting the error while calling the Python inbuilt

sum()

function. To debug it all, we need to do is replace the

[]

bracket with parenthesis.

bill = [1,2,3,4,5]

# solved (using parenthesis bracket to call a function)
total = sum(bill)

print(total)


Output

15


Final Thoughts!

In this Python tutorial, we discussed one of Python’s common errors

TypeError: ‘builtin_function_or_method’ object is not subscriptable

. This error raises in Python when we use the square bracket

[]

to call a Python inbuilt function and method instead of using parenthesis

()

.

The solution to this error is very straightforward. All we need to do is look for the error line code in our source program and check if we are calling the inbuilt function with a square bracket, and replace it with parenthesis.

If you are still getting this error in your Python program, please share your code in the comment section. We will try to help you in debugging.


People are also reading:

  • Python Google Custom Search Engine API

  • Python valueerror: too many values to unpack (expected 2) Solution

  • Automated Browser Testing in Python

  • Python local variable referenced before assignment Solution

  • Python readline() Method

  • Python indexerror: list assignment index out of range Solution

  • Install Python package using Jupyter Notebook

  • Python TypeError: ‘float’ object is not subscriptable Solution

  • Starting Python Coding on a MacBook

  • Python NameError name is not defined Solution

‘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.  

TypeError 'builtin_function_or_method' object is not subscriptable

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.

You generally get typeerror ‘builtin_function_or_method’ object is not subscriptable in Python when you try to use function as array.

someArray = ['Ironman', 'Thor', 'Hulk']
someArray.pop[0]

The above code will generate ‘builtin_function_or_method’ object is not subscriptable error because we are not using pop function properly. We are indexing it as if it was an array but in reality it is a function. You can use the above code correctly like this –

someArray = ['Ironman', 'Thor', 'Hulk']
someArray[0]
// Output: Ironman
someArray.pop(0)
// Output: Ironman

pop[0] should be used as pop(0).

Same thing applies with the set() function. Sets are unordered lists which do not have duplicate values. Sometimes we incorrectly use set like this –

someArray = set[('Ironman', 'Thor', 'Hulk', 'Hulk')]

// TypeError: 'builtin_function_or_method' object is not subscriptable

You can see we have use square bracket [ and parenthesis ( incorrectly. The correct way of doing it is –

someArray = set(['Ironman', 'Thor', 'Hulk', 'Hulk'])

    Tweet this to help others

Other methods related to lists where the error could appear are –

list.append(x) Add an item to the end of the list.
list.extend(L) Extend the list by appending all the items in the given list.
list.insert(i, x) Insert an item at a given position. The first argument is the index of the element before which to insert
list.remove(x) Remove the first item from the list whose value is x.
list.pop([i]) Remove the item at the given position in the list, and return it.
list.index(x) Return the index in the list of the first item whose value is x.
list.count(x) Return the number of times x appears in the list.
list.sort(cmp=None, key=None, reverse=False) Sort the items of the list in place
list.reverse() Reverse the elements of the list, in place.

Live Demo

Open 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-short

In Python, When in built-in function used it must be specify with parenthesis (()) after the name of the function. If you try to run or iterate the program over a built-in method or function without parenthesis (()) the Python will throw exception as “TypeError: builtin_function_or_method is not iterable”.

Let’s consider the scenario of successful execution of a built in function in Python.

fruits = ["Papaya", "Orange", "Grapes", "Watermelon", "Apple"]
print(", ".join(fruits))

In Python, The join() is a built-in function which turns a list into a string and adds a separator between each value in a string. The output of code as below.

Output

Papaya, Orange, Grapes, Watermelon, Apple

In case while writing code, you forget the brackets (()) in built-in function then Python will throw an error. In this below scenerio will throw exception as “TypeError: builtin_function_or_method is not iterable

user = {
    "name": "Saurabh Gupta",
    "age": 35,
    "city": "Noida"
}
#iterate user dictionary
for key, value in user.items:
    print("Key:", key)
    print("Value:", str(value))

Output

File "C:/Users/saurabh.gupta/Desktop/Python Example/test.py", line 7, in <module>
    for key, value in user.items:

TypeError: 'builtin_function_or_method' object is not iterable

The above example is throwing as “TypeError: ‘builtin_function_or_method‘ object is not iterable” because while using items function of dictionary programmer missed to write parenthesis (()) because for loop is iteration operation and it’s required Iterable object but items method is used without parenthesis that’s why Python is considering as object and throwing exception as “TypeError: ‘builtin_function_or_method’ object is not iterable“.

Solution

To resolve such problem related to built-in function or any function always write method with parenthesis (()).

You make correct the above program by writing items method with parenthesis as below in line no 7

user = {
    "name": "Saurabh Gupta",
    "age": 35,
    "city": "Noida"
}
#iterate user dictionary
for key, value in user.items():
    print("Key:", key)
    print("Value:", str(value))

Output

Key: name
Value: Saurabh Gupta
Key: age
Value: 35
Key: city
Value: Noida

Conclusion

This type of exception “TypeError: builtin_function_or_method is not iterable” is common when user forget to use parenthesis (()) while using built-in function.

To learn more on exception handling follow the link Python: Exception Handling.

If this blog for solving TypeError help you to resolve problem make comment or if you know other way to handle this problem write in comment so that it will help others.

“Learn From Others Experience»

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Bsw ошибка ниссан теана l33
  • Bugcheckcode 307 код ошибки