Typeerror list object is not callable как исправить

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

Typeerror list object is not callable error comes when we call list as a function. See, List is a python object which is a group of other python objects. Actually, callable object is those which accepts some arguments and return something. Hence list object is not callable.

Well, the root cause for this error ( list object is not callable ) is straight. It is just because of the invoking list as function. In order to demonstrate it, We will create a list and invoke it.

var_list=[1,2,3,4]
var_list()

Lets run the above code.

"<yoastmark

Typeerror list object is not callable ( Real Scenarios )-

Let’s see some code examples.

Case 1: Incorrectly accessing list element –

Firstly let’s take an example of Incorrectly accessing a list element.

var_list=[1,2,3,6]
element=var_list(0)

Once we execute this code. We get the following output.

Typeerror list object is not callable incorrectly accessing element

list object is not callable incorrectly accessing an element

the correct way to access an individual element is-

Typeerror list object is not callable correctly accessing element

list object is not callable correctly accessing an element

Case 2: Using the list as the variable name –

We all know that we should not use the Python reserve keyword. the list is also one of the reserve python keywords. Suppose if we ignore this fact and use the list as a variable name.

list=[1,2,3,6]
temp=[1,3,5,6]
my_list=list(temp)

Let’s check it out.

list object is not callable list as variable name

list object is not callable list as a variable name

As we can see, we have declared a variable with the name list. But while typecasting when we have used list(). It takes the reference of the declared variable. That’s why the python interpreter throws the same error.

In order to fix this issue, we need to rename the variable. That’s the solution.

Conclusion –

In this article, We have seen the list object is not callable. We have also covered the root cause and its Fix.  Still, If you want to add some more detail on this topic. Please comment below.

Thanks

Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Добавить комментарий