List object is not callable python ошибка

Before you can fully understand what the error means and how to solve, it is important to understand what a built-in name is in Python.

What is a built-in name?

In Python, a built-in name is a name that the Python interpreter already has assigned a predefined value. The value can be either a function or class object. These names are always made available by default, no matter the scope. Some of the values assigned to these names represent fundamental types of the Python language, while others are simple useful.

As of the latest version of Python — 3.6.2 — there are currently 61 built-in names. A full list of the names and how they should be used, can be found in the documentation section Built-in Functions.

An important point to note however, is that Python will not stop you from re-assigning builtin names. Built-in names are not reserved, and Python allows them to be used as variable names as well.

Here is an example using the dict built-in:

>>> dict = {}
>>> dict
{}
>>>

As you can see, Python allowed us to assign the dict name, to reference a dictionary object.

What does «TypeError: ‘list’ object is not callable» mean?

To put it simply, the reason the error is occurring is because you re-assigned the builtin name list in the script:

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

When you did this, you overwrote the predefined value of the built-in name. This means you can no longer use the predefined value of list, which is a class object representing Python list.

Thus, when you tried to use the list class to create a new list from a range object:

myrange = list(range(1, 10))

Python raised an error. The reason the error says «‘list’ object is not callable», is because as said above, the name list was referring to a list object. So the above would be the equivalent of doing:

[1, 2, 3, 4, 5](range(1, 10))

Which of course makes no sense. You cannot call a list object.

How can I fix the error?

If you are getting a similar error such as this one saying an «object is not callable», chances are you used a builtin name as a variable in your code. In this case the fix is as simple as renaming the offending variable. For example, to fix the above code, we could rename our list variable to ints:

ints = [1, 2, 3, 4, 5] # Rename "list" to "ints"
myrange = list(range(1, 10))

for number in ints: # Renamed "list" to "ints"
    if number in myrange:
        print(number, 'is between 1 and 10')

PEP8 — the official Python style guide — includes many recommendations on naming variables.

This is a very common error new and old Python users make. This is why it’s important to always avoid using built-in names as variables such as str, dict, list, range, etc.

Many linters and IDEs will warn you when you attempt to use a built-in name as a variable. If your frequently make this mistake, it may be worth your time to invest in one of these programs.

I didn’t rename a built-in name, but I’m still getting «TypeError: ‘list’ object is not callable». What gives?

Another common cause for the above error is attempting to index a list using parenthesis (()) rather than square brackets ([]). For example:

>>> lst = [1, 2]
>>> lst(0)

Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    lst(0)
TypeError: 'list' object is not callable

For an explanation of the full problem and what can be done to fix it, see TypeError: ‘list’ object is not callable while trying to access a list.

Cover image for How to fix "‘list’ object is not callable" in Python

Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza

The “TypeError: ‘list’ object is not callable” error occurs when you try to call a list (list object) as if it was a function!

Here’s what the error looks like:

Traceback (most recent call last):
  File "/dwd/sandbox/test.py", line 6, in 
    more_items = list(range(11, 20))
                 ^^^^^^^^^^^^^^^^^^^
TypeError: 'list' object is not callable

Enter fullscreen mode

Exit fullscreen mode

Calling a list object as if it’s a callable isn’t what you’d do on purpose, though. It usually happens due to a wrong syntax or overriding a function name with a list object.

Let’s explore the common causes and their solutions.

How to fix TypeError: ‘list’ object is not callable?

This TypeError happens under various scenarios:

  1. Declaring a variable with a name that’s also the name of a function
  2. Indexing a list by parenthesis rather than square brackets
  3. Calling a method that’s also the name of a property
  4. Calling a method decorated with @property

Declaring a variable with a name that’s also the name of a function: A Python function is an object like any other built-in object, such as str, int, float, dict, list, etc.

All built-in functions are defined in the builtins module and assigned a global name for easier access. For instance, list refers to the __builtins__.list function.

That said, overriding a function (accidentally or on purpose) with any value (e.g., a list object) is technically possible.

In the following example, we’ve declared a variable named list containing a list of numbers. In its following line, we try to create another list — this time by using the list() and range() functions:

list = [1, 2, 3, 4, 5, 6, 8, 9, 10] 
# ⚠️ list is no longer pointing to the list function

# Next, we try to generate a sequence to add to the current list
more_items = list(range(11, 20))
# 👆 ⛔ Raises: TypeError: ‘list’ object is not callable

Enter fullscreen mode

Exit fullscreen mode

If you run the above code, Python will complain with a «TypeError: ‘list’ object is not callable» error because we’ve already assigned the list name to the first list object.

We have two ways to fix the issue:

  1. Rename the variable list
  2. Explicitly access the list() function from the builtins module (__bultins__.list)

The second approach isn’t recommended unless you’re developing a module. For instance, if you want to implement an open() function that wraps the built-in open():

# Custom open() function using the built-in open() internally
def open(filename):
     # ...
     __builtins__.open(filename, 'w', opener=opener)
     # ...

Enter fullscreen mode

Exit fullscreen mode

In almost every other case, you should always avoid naming your variables as existing functions and methods. But if you’ve done so, renaming the variable would solve the issue.

So the above example could be fixed like this:

items = [1, 2, 3, 4, 5, 6, 8, 9, 10] 

# Next, we try to generate a sequence to add to the current list
more_items = list(range(11, 20))

Enter fullscreen mode

Exit fullscreen mode

This issue is common with function names you’re more likely to use as variable names. Functions such as vars, locals, list, all, or even user-defined functions.

In the following example, we declare a variable named all containing a list of items. At some point, we call all() to check if all the elements in the list (also named all) are True:

all = [1, 3, 4, True, 'hey there', 1]
# ⚠️ all is no longer pointing to the built-in function all()


# Checking if every element in all is True:
print(all(all))
# 👆 ⛔ Raises TypeError: 'list' object is not callable

Enter fullscreen mode

Exit fullscreen mode

Obviously, we get the TypeError because the built-in function all() is now shadowed by the new value of the all variable.

To fix the issue, we choose a different name for our variable:

items = [1, 3, 4, True, 'hey there', 1]


# Checking if every element in all is True:
print(all(items))
# Output: True

Enter fullscreen mode

Exit fullscreen mode

⚠️ Long story short, you should never use a function name (built-in or user-defined) for your variables!

Overriding functions (and calling them later on) is the most common cause of the «TypeError: ‘list’ object is not callable» error. It’s similar to calling integer numbers as if they’re callables.

Now, let’s get to the less common mistakes that lead to this error.

Indexing a list by parenthesis rather than square brackets: Another common mistake is when you index a list by () instead of []. Based on Python semantics, the interpreter will see any identifier followed by a () as a function call. And since the parenthesis follows a list object, it’s like you’re trying to call a list.

As a result, you’ll get the «TypeError: ‘list’ object is not callable» error.

items = [1, 2, 3, 4, 5, 6]

print(items(2))
# 👆 ⛔ Raises TypeError: 'list' object is not callable

Enter fullscreen mode

Exit fullscreen mode

This is how you’re supposed to access a list item:

items = [1, 2, 3, 4, 5, 6]

print(items[2])
# Output: 3

Enter fullscreen mode

Exit fullscreen mode

Calling a method that’s also the name of a property: When you define a property in a class constructor, it’ll shadow any other attribute of the same name.

class Book:
    def __init__(self, title, authors):
        self.title = title
        self.authors = authors

    def authors(self):
        return self.authors

book = Book('The Pragmatic Programmer', ['David Thomas', 'Andrew Hunt'])
print(book.authors())
# 👆 ⛔ Raises TypeError: 'list' object is not callable

Enter fullscreen mode

Exit fullscreen mode

In the above example, since we have a property named authors, the method authors() is shadowed. As a result, any reference to authors will return the property authors, returning a list object. And if you call this list object value like a function, you’ll get the «TypeError: ‘list’ object is not callable» error.

The name get_authors sounds like a safer and more readable alternative:

class Book:
    def __init__(self, title, authors):
        self.title = title
        self.authors = authors

    def get_authors(self):
        return self.authors

book = Book('The Pragmatic Programmer', ['David Thomas', 'Andrew Hunt'])
print(book.get_authors())
# Output: ['David Thomas', 'Andrew Hunt']

Enter fullscreen mode

Exit fullscreen mode

Calling a method decorated with @property decorator: The @property decorator turns a method into a “getter” for a read-only attribute of the same name. You need to access a getter method without parenthesis, otherwise you’ll get a TypeError.

class Book:
    def __init__(self, title, authors):
        self._title = title
        self._authors = authors

    @property
    def authors(self):
        """Get the authors' names"""
        return self._authors

book = Book('The Pragmatic Programmer', ['David Thomas', 'Andrew Hunt'])
print(book.authors())
# 👆 ⛔ Raises TypeError: 'list' object is not callable

Enter fullscreen mode

Exit fullscreen mode

To fix it, you need to access the getter method without the parentheses:

book = Book('The Pragmatic Programmer', ['David Thomas', 'Andrew Hunt'])
print(book.authors)
# Output: ['David Thomas', 'Andrew Hunt']

Enter fullscreen mode

Exit fullscreen mode

Problem solved!

Alright, I think it does it! I hope this quick guide helped you fix your problem.

Thanks for reading.

❤️ You might like:

  • TypeError: ‘tuple’ object is not callable in Python
  • TypeError: ‘dict’ object is not callable in Python
  • TypeError: ‘str’ object is not callable in Python
  • TypeError: ‘float’ object is not callable in Python
  • TypeError: ‘int’ object is not callable in Python

Уже несколько часов бьюсь, в упор не могу понять в чем проблема, вроде негде здесь косячить.

Задача:
Посчитаем суммарные бюджет и сборы фильмов из таблицы. Напишите функцию column_sum(), которая получает на вход таблицу и номер столбца, и возвращает сумму значений по этому столбцу. Используйте эту функцию, чтобы напечатать результат в таком формате:
Суммарный бюджет: … млн $
Суммарные сборы: … млн $
Суммы выводите с точностью до двух знаков после запятой.
Напоминаем, что бюджет хранится в столбце с индексом 5, а сборы — с индексом 6.

Код:

oscar_data = [
    ['Форма воды', 2017, 6.914, 123, ['фантастика', 'драма'], 19.4, 195.243464],
    ['Лунный свет', 2016, 6.151, 110, ['драма'], 1.5, 65.046687],
    ['В центре внимания', 2015, 7.489, 129, ['драма', 'криминал', 'история'], 20.0, 88.346473],
    ['Бёрдмэн', 2014, 7.604, 119, ['драма', 'комедия'], 18.0, 103.215094],
    ['12 лет рабства', 2013, 7.71, 133, ['драма', 'биография', 'история'], 20.0, 178.371993],
    ['Операция "Арго"', 2012, 7.517, 120, ['триллер', 'драма', 'биография'], 44.5, 232.324128],
    ['Артист', 2011, 7.942, 96, ['драма', 'мелодрама', 'комедия'], 15.0, 133.432856],
    ['Король говорит!', 2010, 7.977, 118, ['драма', 'биография', 'история'], 15.0, 414.211549],
    ['Повелитель бури', 2008, 7.298, 126, ['триллер', 'драма', 'военный', 'история'], 15.0, 49.230772],
    ['Миллионер из трущоб', 2008, 7.724, 120, ['драма', 'мелодрама'], 15.0, 377.910544],
    ['Старикам тут не место', 2007, 7.726, 122, ['триллер', 'драма', 'криминал'], 25.0, 171.627166],
    ['Отступники', 2006, 8.456, 151, ['триллер', 'драма', 'криминал'], 90.0, 289.847354],
    ['Столкновение', 2004, 7.896, 108, ['триллер', 'драма', 'криминал'], 6.5, 98.410061],
    ['Малышка на миллион', 2004, 8.075, 132, ['драма', 'спорт'], 30.0, 216.763646],
    ['Властелин колец: Возвращение Короля', 2003, 8.617, 201, ['фэнтези', 'драма', 'приключения'], 94.0, 1119.110941],
    ['Чикаго', 2002, 7.669, 113, ['мюзикл', 'комедия', 'криминал'], 45.0, 306.776732],
    ['Игры разума', 2001, 8.557, 135, ['драма', 'биография', 'мелодрама'], 58.0, 313.542341],
    ['Гладиатор', 2000, 8.585, 155, ['боевик', 'драма', 'приключения'], 103.0, 457.640427],
    ['Красота по-американски', 1999, 7.965, 122, ['драма'], 15.0, 356.296601],
    ['Влюбленный Шекспир', 1998, 7.452, 123, ['драма', 'мелодрама', 'комедия', 'история'], 25.0, 289.317794],
    ['Титаник', 1997, 8.369, 194, ['драма', 'мелодрама'], 200.0, 2185.372302],
    ['Английский пациент', 1996, 7.849, 155, ['драма', 'мелодрама', 'военный'], 27.0, 231.976425],
    ['Храброе сердце', 1995, 8.283, 178, ['драма', 'военный', 'биография', 'история'], 72.0, 210.409945],
    ['Форрест Гамп', 1994, 8.915, 142, ['драма', 'мелодрама'], 55.0, 677.386686],
    ['Список Шиндлера', 1993, 8.819, 195, ['драма', 'биография', 'история'], 22.0, 321.265768],
    ['Непрощенный', 1992, 7.858, 131, ['драма', 'вестерн'], 14.4, 159.157447],
    ['Молчание ягнят', 1990, 8.335, 114, ['триллер', 'криминал', 'детектив', 'драма', 'ужасы'], 19.0, 272.742922],
    ['Танцующий с волками', 1990, 8.112, 181, ['драма', 'приключения', 'вестерн'], 22.0, 424.208848],
    ['Шофёр мисс Дэйзи', 1989, 7.645, 99, ['драма'], 7.5, 145.793296],
    ['Человек дождя', 1988, 8.25, 133, ['драма'], 25.0, 354.825435],
]


def column_sum(data, column):
    result = 0
    for row in data:
        result += row(column)
    return result

total_budget = column_sum(oscar_data, 5)
print('Суммарный бюджет: {:.2f} млн $'.format(total_budget))

total_gross = column_sum(oscar_data, 6)
print('Суммарные сборы: {:.2f} млн $'.format(total_gross))

Ошибка:

Traceback (most recent call last):
  File "main.py", line 41, in <module>
    print(column_sum(oscar_data, 5)) 
  File "main.py", line 38, in column_sum
    result += row(column)
TypeError: 'list' object is not callable

In this Python tutorial, we will discuss how to fix “typeerror and attributeerror” in python. We will check:

  • TypeError: ‘list’ object is not callable.
  • TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’.
  • Python object has no attribute
  • TypeError: python int object is not subscriptable

In python, we get this error when we pass the argument inside the print statement, the code contains the round bracket to print each item in the list due to which we get this typeerror.

Example:

my_list = ["Kiyara", "Elon", "John", "Sujain"]
for value in range(len(my_list)):
print(my_list(value))

After writing the above code, Ones you will print “my_list(value)” then the error will appear as a “ TypeError: ‘list’ object is not callable  ”. Here, this error occurs because we are using the round bracket which is not correct for printing the items.

You can see the below screenshot for this typeerror in python

TypeError: 'list' object is not callable
TypeError: ‘list’ object is not callable

To solve this python typeerror we have to pass the argument inside the square brackets while printing the “value” because the list variable works in this way.

Example:

my_list = ["Kiyara", "Elon", "John", "Sujain"]
for value in range(len(my_list)):
print(my_list[value])

After writing the above code, Ones you will print “ my_list[value] ” then the output will appear as a “ Kiyara Elon John Sujain ”. Here, the error is resolved by giving square brackets while printing.

You can refer to the below screenshot how typeerror is resolved.

Python error list object is not callable
Python error list object is not callable

TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

We get unsupported operand type(s) for +: ‘int’ and ‘str’ error when we try to add an integer with string or vice versa as we cannot add a string to an integer.

Example:

a1 = 10
a2 = "5"
s = a1 + a2
print(s)

After writing the above code, Ones you will print “(s)” then the error will appear as a  TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’  ”. Here, this error occurs because we are trying to add integer and string so it returns an error.

You can see the below screenshot typeerror: unsupported operand type(s) for +: ‘int’ and ‘str’ in python

TypeError: unsupported operand type(s) for +: 'int' and 'str'
TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

To solve this python typeerror we have to convert the string value to an integer using the int() method so, in this way we can avoid this error.

Example:

a1 = 10
a2 = "5"
s = a1 + int(a2
)
print(s)

After writing the above code, Ones you will print “ (s) ” then the output will appear as a “ 15 ”. Here, the error is resolved by converting the value of a2 to an integer type, and then it added two values.

You can refer to the below screenshot of how unsupported operand type(s) for +: ‘int’ and ‘str’ is resolved.

unsupported operand type(s) for +: 'int' and 'str'
unsupported operand type(s) for +: ‘int’ and ‘str’

Python object has no attribute

In python, we get this attribute error because of invalid attribute reference or assignment.

Example:

a = 10
a.append(20)
print(a)

After writing the above code, Ones you will print “a” then the error will appear as an “ AttributeError: ‘int’ object has no attribute ‘append’ ”. Here, this error occurs because of invalid attribute reference is made and variable of integer type does not support append method.

You can see the below screenshot for attribute error

Python object has no attribute
Python object has no attribute

To solve this python attributeerror we have to give a variable of list type to support the append method in python, so it is important to give valid attributes to avoid this error.

Example:

roll = ['1','2','3','4']
roll.append('5')
print('Updated roll in list: ',roll)

After writing the above code, Ones you will print then the output will appear as an “Updated roll in list: [‘1’, ‘2’, ‘3’, ‘4’, ‘5’] ”. Here, the error is resolved by giving the valid attribute reference append on the list.

You can refer to the below screenshot how attributeerror is resolved.

Python object has no attribute 1

Python object has no attribute

TypeError: python int object is not subscriptable

This error occurs when we try to use integer type value as an array. We are treating an integer, which is a whole number, like a subscriptable object. Integers are not subscriptable object. An object like tuples, lists, etc is subscriptable in python.

Example:

v_int = 1
print(v_int[0])
  • After writing the above code, Once you will print “ v_int[0] ” then the error will appear as a “ TypeError: ‘int’ object is not subscriptable ”.
  • Here, this error occurs because the variable is treated as an array by the function, but the variable is an integer.
  • You can see we have declared an integer variable “v_int” and in the next line, we are trying to print the value of integer variable “v_int[0]” as a list. Which gives the error.

You can see the below screenshot for typeerror: python int object is not subscriptable

TypeError: python int object is not subscriptable
TypeError: python int object is not subscriptable

To solve this type of error ‘int’ object is not subscriptable in python, we need to avoid using integer type values as an array. Also, make sure that you do not use slicing or indexing to access values in an integer.

Example:

v_int = 1
print(v_int)

After writing the above code, Once you will print “ v_int ” then the output will appear as “ 1 ”. Here, the error is resolved by removing the square bracket.

You can see the below screenshot for typeerror: python int object is not subscriptable

typeerror: python int object is not subscriptable
typeerror: python int object is not subscriptable

You may like the following Python tutorials:

  • Python if else with examples
  • Python For Loop with Examples
  • Python read excel file and Write to Excel in Python
  • Create a tuple in Python
  • Python create empty set
  • Python Keywords with examples
  • Python While Loop Example
  • String methods in Python with examples
  • NameError: name is not defined in Python
  • Python check if the variable is an integer

This is how to fix python TypeError: ‘list’ object is not callable, TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’, AttributeError: object has no attribute and TypeError: python int object is not subscriptable

Fewlines4Biju Bijay

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Table of Contents
Hide
  1. Python TypeError: ‘list’ object is not callable
    1. Scenario 1 – Using the built-in name list as a variable name
    2. Solution for using the built-in name list as a variable name
    3. Scenario 2 – Indexing list using parenthesis()
    4. Solution for Indexing list using parenthesis()
  2. Conclusion

The most common scenario where Python throws TypeError: ‘list’ object is not callable is when you have assigned a variable name as “list” or if you are trying to index the elements of the list using parenthesis instead of square brackets.

In this tutorial, we will learn what ‘list’ object is is not callable error means and how to resolve this TypeError in your program with examples.

There are two main scenarios where you get a ‘list’ object is not callable error in Python. Let us take a look at both scenarios with examples.

Scenario 1 – Using the built-in name list as a variable name

The most common mistake the developers tend to perform is declaring the Python built-in names or methods as variable names.

What is a built-in name?

In Python, a built-in name is nothing but the name that the Python interpreter already has assigned a predefined value. The value can be either a function or class object. 

The Python interpreter has 70+ functions and types built into it that are always available.

In Python, a list is a built-in function, and it is not recommended to use the built-in functions or keywords as variable names.

Python will not stop you from using the built-in names as variable names, but if you do so, it will lose its property of being a function and act as a standard variable.

Let us take a look at a simple example to demonstrate the same.

fruit = "Apple"
list = list(fruit)
print(list)

car="Ford"
car_list=list(car)
print(car_list)

Output

['A', 'p', 'p', 'l', 'e']
Traceback (most recent call last):
  File "c:PersonalIJSCodemain.py", line 6, in <module>
    car_list=list(car)
TypeError: 'list' object is not callable

If you look at the above example, we have declared a fruit variable, and we are converting that into a list and storing that in a new variable called “list“.

Since we have used the “list” as a variable name here, the list() method will lose its properties and functionality and act like a normal variable.

We then declare a new variable called “car“, and when we try to convert that into a list by creating a list, we get TypeError: ‘list’ object is not callable error message. 

The reason for TypeError is straightforward we have a list variable that is not a built function anymore as we re-assigned the built-in name list in the script. This means you can no longer use the predefined list value, which is a class object representing the Python list.

Solution for using the built-in name list as a variable name

If you are getting object is not callable error, that means you are simply using the built-in name as a variable in your code. 

fruit = "Apple"
fruit_list = list(fruit)
print(fruit_list)

car="Ford"
car_list=list(car)
print(car_list)

Output

['A', 'p', 'p', 'l', 'e']
['F', 'o', 'r', 'd']

In our above code, the fix is simple we need to rename the variable “list” to “fruit_list”, as shown below, which will fix the  ‘list’ object is not callable error. 

Scenario 2 – Indexing list using parenthesis()

Another common cause for this error is if you are attempting to index a list of elements using parenthesis() instead of square brackets []. The elements of a list are accessed using the square brackets with index number to get that particular element.

Let us take a look at a simple example to reproduce this scenario.

my_list = [1, 2, 3, 4, 5, 6]
first_element= my_list(0)
print(" The first element in the list is", first_element)

Output

Traceback (most recent call last):
  File "c:PersonalIJSCodetempCodeRunnerFile.py", line 2, in <module>
    first_element= my_list(0)
TypeError: 'list' object is not callable

In the above program, we have a “my_list” list of numbers, and we are accessing the first element by indexing the list using parenthesis first_element= my_list(0), which is wrong. The Python interpreter will raise TypeError: ‘list’ object is not callable error. 

Solution for Indexing list using parenthesis()

The correct way to index an element of the list is using square brackets. We can solve the ‘list’ object is not callable error by replacing the parenthesis () with square brackets [] to solve the error as shown below.

my_list = [1, 2, 3, 4, 5, 6]
first_element= my_list[0]
print(" The first element in the list is", first_element)

Output

 The first element in the list is 1

Conclusion

The TypeError: ‘list’ object is not callable error is raised in two scenarios 

  1. If you try to access elements of the list using parenthesis instead of square brackets
  2. If you try to use built-in names such as list as a variable name 

Most developers make this common mistake while indexing the elements of the list or using the built-in names as variable names. PEP8 – the official Python style guide – includes many recommendations on naming variables properly, which can help beginners.

A list in Python is used to store various elements/items in a variable. While working with lists, you may encounter a “TypeError: list object is not callable” for various reasons.  Such as, the stated error occurs when you try to access a list incorrectly, overriding a list, accessing a list as a function, etc. The TypeError can be resolved via different approaches.

This write-up will provide you with a reason, and solution for TypeError “list object is not callable” in Python with numerous examples. The following aspects will be discussed in this write-up one by one:

  • Reason 1: Incorrect Accessing of List
  • Solution: Access to the List Correctly
  • Reason 2: Overriding list() Function
  • Solution: Rename List Variable
  • Reason 3: Calling List as a Function
  • Solution: Remove Parentheses From the List
  • Reason 4: Same Function Name and Variable
  • Solution: Rename List Variable/Function

So, let’s get started!

Reason 1: Incorrect Accessing of List

The first possible reason for the TypeError is when the list is wrongly accessed in the program. This means that the list is assessed using parentheses.

An example of this error is shown in the below code snippet.

Code:

In the above code, the error arises at the time of accessing when the parentheses are used instead of brackets inside the print() function.

Output:

The above output shows the “TypeError”.

Solution: Access the List Correctly

To remove this error, square brackets must be placed in the place of parentheses. The following code given below shows the solution:

Code:

List_Value = ['Alex', 'Blake', 'Candy']

print(List_Value[0])

In the above code, the error is corrected using the bracket instead of parentheses for accessing the list element.

Output:

The above output shows that the list element has been accessed successfully.

.

Reason 2: Overriding list() Function

Another possibility of the “TypeError” is when the “list()” function is overridden while initializing the list variable. An example of list overriding is shown in the below code snippet.

Code:

In the above code, the list is overridden inside the print() function.

Output:

The above output shows the “TypeError”.

Solution: Rename List Variable

To remove the stated error, the list variable must be renamed. After renaming, re-execute the program, and the error will be gone. Have a look at the following snippet below:

Code:

new_List = ['Alex', 'Blake', 'Candy']

print(list([1, 2, 3]))

In the above code, the first list variable name has been renamed and after that new list will be executed and printed on the screen without any error.

Output:

The above output shows the list values.

Reason 3: Calling List as a Function

This error also occurs when the list variable is called like a function. The below code shows how the stated error occurs when we call a list as a function.

Code:

In the above code, the list is called as a function “new_list()” i.e. without using brackets or any integer value inside it.

Output:

The above output shows the “TypeError”.

Solution: Removing the Parentheses From the List

To remove this error, we have to remove the parentheses or use the square bracket with index value to access any element of the list. The below code shows the solution to this error:

Code:

new_List = ['Alex', 'Blake', 'Candy']

print(new_List)

In the above code, the parentheses are removed from the list variable inside the print() function.

Output:

The above output shows the value of the list.

Reason 4: Same Function Name and Variable

The “TypeError: list object is not callable” occurs when the function and list variable are initialized in a Python script with the same name.

Code:

The function and the list variable in the above code are initialized with the same name, “value”.

Output:

The above output shows the “TypeError”.

Solution: Rename List Variable/Function

To remove the error, change the name of the function or the name of the list variable. The program below shows the solution to the error.

Code:

def value():
    return 'its-linux-foss'

value_1 = ['Alex', 'Blake', 'Candy']

print(value())

In the above code, the name of the list variable is changed from “value” to “value_1”.

Output:

The above output shows the value of the function.

That’s it from this guide!

Conclusion

The “TypeError: ‘list’ object is not callable” occurs in Python due to incorrect accessing of the list, calling list as a function, overriding list variable, same function, and list variable name. To access a specific value of the list, use a square bracket and pass the desired index number within the square bracket. To resolve the stated error, access the list appropriately, don’t override the list, don’t access the list as a function, etc. This article presented a detailed guide on how to fix the type error “list object is not callable” in Python.

Если вы работаете со списками в Python, вы могли столкнуться с ошибкой типа «Ошибка типа: объект «список» не может быть вызван в Python». Эта ошибка может быть весьма неприятной, особенно если вы не знаете, что она означает и как ее исправить. В этом сообщении блога мы подробно рассмотрим ошибку «TypeError: объект list» не может быть вызван в Python, что ее вызывает и как ее исправить.

Сообщение об ошибке «Ошибка типа: объект «список» не вызывается в Python» — это распространенное сообщение об ошибке, с которым вы можете столкнуться при работе со списками в Python. Эта ошибка возникает, когда вы пытаетесь использовать круглые скобки для вызова списка, но Python рассматривает это как вызов функции.

Например, предположим, что у вас есть список, содержащий некоторые значения:

my_list = [1, 2, 3, 4]

Войти в полноэкранный режимВыйти из полноэкранного режима

Если вы попытаетесь вызвать список как функцию следующим образом:

my_list()

Войти в полноэкранный режимВыйти из полноэкранного режима

Вы получите сообщение об ошибке, подобное этому:

TypeError: 'list' object is not callable

Войти в полноэкранный режимВыйти из полноэкранного режима

Это сообщение об ошибке сообщает вам, что вы пытаетесь вызвать список как функцию, что невозможно.

Что вызывает ошибку «TypeError: объект list» не может быть вызван в Python?

Ошибка «TypeError: объект list не вызывается в Python» возникает, когда вы пытаетесь использовать круглые скобки для вызова списка, но Python рассматривает это как вызов функции. Это может произойти по разным причинам, но наиболее распространенной причиной является конфликт имен.

Например, предположим, что у вас есть функция с именем my_list, которая принимает некоторые параметры и возвращает список:

def my_list(arg1, arg2):
    # Do something with the arguments
    return [arg1, arg2]

Войти в полноэкранный режимВыйти из полноэкранного режима

Теперь, если вы создадите список с тем же именем, что и функция:

my_list = [1, 2, 3, 4]

Войти в полноэкранный режимВыйти из полноэкранного режима

И попробуйте вызвать функцию:

my_list()

Войти в полноэкранный режимВыйти из полноэкранного режима

Вы получите ошибку «TypeError: объект list не может быть вызван в Python».

Другой распространенной причиной этой ошибки является забывание использовать оператор индекса ([]), который используется для доступа к элементам списка. Например, если у вас есть список:

my_list = [1, 2, 3, 4]

Войти в полноэкранный режимВыйти из полноэкранного режима

И вы пытаетесь получить доступ к элементу следующим образом:

my_list(0)

Войти в полноэкранный режимВыйти из полноэкранного режима

Вы получите ошибку «TypeError: объект list не может быть вызван в Python».

Как исправить ошибку «TypeError: объект list не может быть вызван в Python»

Существует несколько различных способов исправить ошибку «TypeError: объект list» не может быть вызван в Python, в зависимости от причины. Вот несколько различных подходов, которые вы можете использовать:

Подход 1: переименовать список

Если ошибка вызвана конфликтом имен, один из способов исправить ее — переименовать либо список, либо функцию. Например, вы можете переименовать список:

my_list = [1, 2, 3, 4]
result = my_list.pop()
print(result)

Войти в полноэкранный режимВыйти из полноэкранного режима

Это выведет:

4

Войти в полноэкранный режимВыйти из полноэкранного режима

Подход 2: использование оператора индекса

Если ошибка вызвана тем, что вы забыли использовать оператор индекса ([]), вы можете исправить это, используя правильный синтаксис для доступа к элементам списка. Например:

my_list = [1, 2, 3, 4]
result = my_list[0]
print(result)

Войти в полноэкранный режимВыйти из полноэкранного режима

Это выведет:

1

Войти в полноэкранный режимВыйти из полноэкранного режима

Подход 3: определение новой функции

Если ошибка вызвана перезаписью функции списком, вы можете определить новую функцию с другим именем. Например:

def my_function(arg1, arg2):
    return [arg1, arg2]

my_list = [1, 2, 3, 4]

def new_function(some_list):
    # Do something with the list
    pass

new_function(my_list)

Войти в полноэкранный режимВыйти из полноэкранного режима

Это приведет к вызову новой функции со списком в качестве аргумента без каких-либо ошибок.

Подход 4: исправление синтаксических ошибок

Если ошибка вызвана синтаксическими ошибками, вы можете исправить их, внимательно просмотрев свой код и убедившись, что используете правильный синтаксис. Например:

my_list = [1, 2, 3, 4]
if len(my_list) == 4:
    print('The list has four elements')
else:
    print('The list does not have four elements')

Войти в полноэкранный режимВыйти из полноэкранного режима

Это выведет:

The list has four elements

Войти в полноэкранный режимВыйти из полноэкранного режима

Заключение

Ошибка ‘TypeError: ‘list’ object is not callable in Python’ может быть весьма неприятной, особенно если вы не знаете, что ее вызывает и как ее исправить. Однако, поняв распространенные причины этой ошибки и различные подходы к ее устранению, вы сможете легко преодолеть эту ошибку и продолжить работу со списками в Python. Не забудьте внимательно просмотреть свой код, чтобы выявить и исправить любые синтаксические ошибки и всегда использовать правильный синтаксис при работе со списками.

When you try to access items in a list using curly brackets ( () ), Python returns an error. This is because Python thinks that you are trying to call a function.

In this guide, we talk about the Python “typeerror: ‘list’ object is not callable” error and why it is raised. We’ll walk through an example scenario to help you learn how to fix this error. Let’s begin!

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.

The Problem: typeerror: ‘list’ object is not callable

Python already tells us all we need to know in this error:

typeerror: 'list' object is not callable

Take a look at the error type: TypeError. This is one of the most common types of Python errors. It tells us we’re trying to manipulate a value using a method not available to the type of data in which the value is stored.

Our error message tells us that we’re trying to call a Python list object. This means we are treating it like a function rather than as a list.

This error is raised when you use curly brackets to access items in a list. Consider the following list of scones:

scones = ["Cherry", "Apple and Cinnamon", "Plain", "Cheese"]

To access items in this list, we must state the index number of the value we want to access enclosed by square brackets:

This returns: Cherry. 0 is the position of the first item in our list, “Cherry”.

An Example Scenario

We’re going to build a Python program that capitalizes a list of names. We must capitalize the first letters of these names because they are going to be printed out on name cards.

Start by declaring a list of names:

names = ["Peter Geoffrey", "Dakota Williams", "Rebecca Lee"]

Next, create a for loop that iterates through this list of names. We’ll convert each name to upper case and replace the lowercase name with the uppercase name in the list:

for n in range(len(names)):
	names[n] = names(n).upper()
	print(names(n))

print(names)

Use the range() method to iterate through every item in the “names” list. Then use the assignment operator to change the value of each name to its uppercase equivalent. The Python upper() method converts each name to uppercase.

Next, print out the new name to the console. Once our loop has run, print out the whole revised list to the console.

Let’s run our code:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
	names[n] = names(n).upper()
TypeError: 'list' object is not callable

We’ve received an error, as expected. Let’s solve this problem.

The Solution

Use square brackets to access items in a list. Curly brackets are used to call functions in Python. The problem in our code is that we’re trying to call a list as a function because we’re using curly brackets to access items in our list.

In our code, use curly brackets to access a list item in two places:

for n in range(len(names)):
names[n] = names(n).upper()
print(names(n))

We must swap the names(n) code to use square brackets: 

for n in range(len(names)):
names[n] = names[n].upper()
print(names[n])

This tells Python we want to access the item at the index position “n” in the list “names”.

Run our code with the applicable revisions we just discussed:

PETER GEOFFREY
DAKOTA WILLIAMS
REBECCA LEE

['PETER GEOFFREY', 'DAKOTA WILLIAMS', 'REBECCA LEE']

This time, a successful response returns. Every name is converted into capital letters.

The version of a name in capital letters replaces the sentence-case version of the name. Then, we print out each name to the console. When our program is done, we print out a list of all the names in “names” to check that they have been changed in our list.

Conclusion

The Python “typeerror: ‘list’ object is not callable” error is raised when you try to access a list as if it were a function. To solve this error, make sure square brackets are used to access or change values in a list rather than curly brackets.

Now you’re ready to fix this error in your code like a professional Python developer!

In this article, we will be discussing the TypeError: “List” Object is not callable exception. We will also be through solutions to this problem with example programs.

Why Is this Error Raised?

This exception is raised when a list type is accessed as a function or the predefined term “list” is overwritten. The cause for these two situations are the following:

  1. list” being used as a variable name.
  2. Using parenthesis for list indexing

list” Being Used as a Variable Name

Variable declaration using in-built names or functions is a common mistake in rookie developers. An in-built name is a term with its value pre-defined by the language itself. That term can either be a method or an object of a class.

list() is an in-built Python function. As we discussed, it is not advisable to use pre-defined names as variable names. Although using a predefined name will not throw any exception in itself, the function under the name will no longer be accessible.

Let’s refer to an example.

website = "PythonPool"
list = list(website)
print(list)

content = "Python Material"
contentList = list(content)
print(contentList)

Output and Explanation

list object not callable

  1. The variable website consists of PythonPool
  2. The variable website is stored in the variable list as a list using list()
  3. We print the variable list, producing the required output.
  4. Similarly, another variable content stores “Python Material”
  5. We use list() and pass content as argument.
  6. Upon printing contentList, we get the mentioned error.

What went wrong here? In step 2, we store the list type in a variable called list, which is a predefined function. When were try to use the list function again in step 5, it fails. Python only remembers list as a variable since step 2. Therefore, list() has lost all functionality after being declared as a variable.

Solution

Instead of using list as a variable declaration, we can use more descriptive variable names that are not pre-defined (myList, my_list, nameList). For programming, follow PEP 8 naming conventions.

website = "PythonPool"
myList = list(website)
print(myList)

content = "Python Material"
contentList = list(content)
print(contentList)

Correct Output

['P', 'y', 't', 'h', 'o', 'n', 'P', 'o', 'o', 'l']
['P', 'y', 't', 'h', 'o', 'n', ' ', 'M', 'a', 't', 'e', 'r', 'i', 'a', 'l']

Using Parenthesis for List Indexing

Using parenthesis “()” instead of square brackets “[]” can also give rise to TypeError: List Object is not callable. Refer to the following demonstration:

myList = [2, 4, 6, 8, 10]
lastElement = myList(4)
print("the final element is: ", lastElement)

Output and Explanation

 Parenthesis for List Indexing Error

  1. Variable myList consists of a list of integers.
  2. We are accessing the last index element and storing it in lastElement.
  3. Finally, we are printing lastElement.

In line 2, we are accessing the final element of the list using parenthesis (). This is syntactically wrong. Indexing in Python lists requires that you pass the index values in square brackets.

Solution

Use square brackets in place of parenthesis.

myList = [2, 4, 6, 8, 10]
lastElement = myList[4]
print("the final element is: ", lastElement)

Correct Output

the final element is:  10

Python Error: “list” Object Not Callable with For Loop

def main():
     myAccounts=[]

     numbers=eval(input())

          ...
          ...
          ...
          ...

          while type!='#':
               ...
               ...
                 for i in range(len(myAccounts())): 
                        if(account==myAccounts[i].getbankaccount()):
                        index=i
                        ...
                        ...
main()

Output and Explanation

 Traceback(most recent call last):
....
....
     for i in range(len(myAccounts())):
     TypeError: 'list' object is not callable

The problem here is that in for i in range(len(myAccounts())): we have called myAccounts(). This is a function call. However, myAccounts is a list type.

Solution

Instead of calling myAccounts as a function, we will be calling it as a list variable.

def main():
     myAccounts=[]

     numbers=eval(input())

          ...
          ...
          ...
          ...

          while type!='#':
               ...
               ...
                 # for i in range(len(myAccounts)): 
                        if(account==myAccounts[i].getbankaccount()):
                        index=i
                        ...
                        ...
main()
nums = [3,6,9,10,12]
list = list(nums)
print(list)

LambdaList = [1,2,3,4,5,6,7,8,9]
myList = list(filter(lambda a:(a%2==0), LamdaList))
print(myList)

Output and Explanation

 LambdaList = [1,2,3,4,5,6,7,8,9]
 myList = list(filter(lambda a:(a%2==0), list1))
 print(myList)

TypeError: 'list' object is not callable

list is used in line 2. This removes all functionality of the list function at line 5.

Solution

Avoid using pre-defined variable names.

nums = [3,6,9,10,12]
numList = list(nums)
print(numList)

LambdaList = [1,2,3,4,5,6,7,8,9]
myList = list(filter(lambda a:(a%2==0), LamdaList))
print(myList)

wb.sheetnames() TypeError: ‘list’ Object Is Not Callable

import openpyxl

mySheet = openpyxl.load_workbook("Sample.xlsx")
names = mySheet.sheetnames

print(names)
print(type(mySheet))

Output and Explanation

TypeError: 'list' object is not callable

In line 3, we have called mySheet.sheetnames. To get the name of all the sheets, do:

import openpyxl

mySheet = openpyxl.load_workbook("Sample.xlsx")
names = mySheet.sheet_names()

print(names)
print(type(mySheet))

# to access specific sheets
mySheet.get_sheet_by_name(name = 'Sheet 1') 

Efficiently Organize Your Data with Python Trie

TypeError: ‘list’ Object is Not Callable in Flask

server.py

@server.route('/devices',methods = ['GET'])
def status(): 
    return app.stat()

if __name__ == '__main__':
        app.run()

app.py

def stat():
    return(glob.glob("/myPort/2203") + glob.glob("/alsoMyPort/3302"))

test.py

url = "http://1278.3.3.1:1000"

response = requests.get(url + " ").text
print(response)

Output and Explanation

"TypeError": 'list' object is not callable.

The final result is a list. In flask, the only two valid return types are strings or response types (JSON).

Solution

Make sure the return type is a string.

@server.route('/myDevices')
def status():
    return ','.join(app.devicesStats())

FAQs

What is a TypeError?

Python has several standard exceptions, including TypeError. When an operation is performed on an incorrect object type, a TypeError is raised.

How do we check if the object is a list before using its method?

In order to check if it is a list object, we can pass the isinstance() function like so:
if isinstance(myList, list):
  print("valid list)
else:
    print("invalid list")

Trending Python Articles

  • [Fixed] SSL module in Python is Not Available

    [Fixed] SSL module in Python is Not Available

    May 30, 2023

  • [Fixed] modulenotfounderror: no module named ‘_bz2

    [Fixed] modulenotfounderror: no module named ‘_bz2

    by Namrata GulatiMay 2, 2023

  • [Fixed] Cannot Set verify_mode to cert_none When check_hostname is Enabled

    [Fixed] Cannot Set verify_mode to cert_none When check_hostname is Enabled

    by Namrata GulatiMay 2, 2023

  • Prevent Errors with Python deque Empty Handling

    Prevent Errors with Python deque Empty Handling

    by Namrata GulatiMay 2, 2023

Понравилась статья? Поделить с друзьями:
  • List object has no attribute append ошибка
  • List assignment index out of range python ошибка
  • Lisbor кондиционер коды ошибок
  • Lisa goes to the cinema now исправьте ошибки
  • Lirika saeco кофемашина выдает ошибку