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.

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!

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

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.

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!

Возможно, вам также будет интересно:

  • Bugsplat ошибка company of heroes 2
  • Bugcheckcode 307 код ошибки
  • Bugcheck 1001 windows 10 ошибка синий экран
  • Bugcheck 1001 windows 10 ошибка 0x00000133
  • Bugcheck 1001 windows 10 ошибка 0x0000007e

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

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