List object is not callable python как исправить

TypeError: ‘list’ object is not callable occurs when you declare list as variable name or if you access elements of list using parenthesis()
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.

Have you ever seen the TypeError object is not callable when running one of your Python programs? We will find out together why it occurs.

The TypeError object is not callable is raised by the Python interpreter when an object that is not callable gets called using parentheses. This can occur, for example, if by mistake you try to access elements of a list by using parentheses instead of square brackets.

I will show you some scenarios where this exception occurs and also what you have to do to fix this error.

Let’s find the error!

What Does Object is Not Callable Mean?

To understand what “object is not callable” means we first have understand what is a callable in Python.

As the word callable says, a callable object is an object that can be called. To verify if an object is callable you can use the callable() built-in function and pass an object to it. If this function returns True the object is callable, if it returns False the object is not callable.

callable(object)

Let’s test this function with few Python objects…

Lists are not callable

>>> numbers = [1, 2, 3]
>>> callable(numbers)
False

Tuples are not callable

>>> numbers = (1, 2, 3)
>>> callable(numbers)
False

Lambdas are callable

>>> callable(lambda x: x+1)
True

Functions are callable

>>> def calculate_sum(x, y):
...     return x+y
... 
>>> callable(calculate_sum)
True

A pattern is becoming obvious, functions are callable objects while data types are not. And this makes sense considering that we “call” functions in our code all the time.

What Does TypeError: ‘int’ object is not callable Mean?

In the same way we have done before, let’s verify if integers are callable by using the callable() built-in function.

>>> number = 10
>>> callable(number)
False

As expected integers are not callable 🙂

So, in what kind of scenario can this error occur with integers?

Create a class called Person. This class has a single integer attribute called age.

class Person:
    def __init__(self, age):
        self.age = age

Now, create an object of type Person:

john = Person(25)

Below you can see the only attribute of the object:

print(john.__dict__)
{'age': 25}

Let’s say we want to access the value of John’s age.

For some reason the class does not provide a getter so we try to access the age attribute.

>>> print(john.age())
Traceback (most recent call last):
  File "callable.py", line 6, in <module>
    print(john.age())
TypeError: 'int' object is not callable

The Python interpreter raises the TypeError exception object is not callable.

Can you see why?

That’s because we have tried to access the age attribute with parentheses.

The TypeError‘int’ object is not callable occurs when in the code you try to access an integer by using parentheses. Parentheses can only be used with callable objects like functions.

What Does TypeError: ‘float’ object is not callable Mean?

The Python math library allows to retrieve the value of Pi by using the constant math.pi.

I want to write a simple if else statement that verifies if a number is smaller or bigger than Pi.

import math

number = float(input("Please insert a number: "))

if number < math.pi():
    print("The number is smaller than Pi")
else:
    print("The number is bigger than Pi")

Let’s execute the program:

Please insert a number: 4
Traceback (most recent call last):
  File "callable.py", line 12, in <module>
    if number < math.pi():
TypeError: 'float' object is not callable

Interesting, something in the if condition is causing the error ‘float’ object is not callable.

Why?!?

That’s because math.pi is a float and to access it we don’t need parentheses. Parentheses are only required for callable objects and float objects are not callable.

>>> callable(4.0)
False

The TypeError‘float’ object is not callable is raised by the Python interpreter if you access a float number with parentheses. Parentheses can only be used with callable objects.

What is the Meaning of TypeError: ‘str’ object is not callable?

The Python sys module allows to get the version of your Python interpreter.

Let’s see how…

>>> import sys
>>> print(sys.version())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

No way, theobject is not callable error again!

Why?

To understand why check the official Python documentation for sys.version.

Python sys version

That’s why!

We have added parentheses at the end of sys.version but this object is a string and a string is not callable.

>>> callable("Python")
False

The TypeError‘str’ object is not callable occurs when you access a string by using parentheses. Parentheses are only applicable to callable objects like functions.

Error ‘list’ object is not callable when working with a List

Define the following list of cities:

>>> cities = ['Paris', 'Rome', 'Warsaw', 'New York']

Now access the first element in this list:

>>> print(cities(0))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable

What happened?!?

By mistake I have used parentheses to access the first element of the list.

To access an element of a list the name of the list has to be followed by square brackets. Within square brackets you specify the index of the element to access.

So, the problem here is that instead of using square brackets I have used parentheses.

Let’s fix our code:

>>> print(cities[0])
Paris

Nice, it works fine now.

The TypeError‘list’ object is not callable occurs when you access an item of a list by using parentheses. Parentheses are only applicable to callable objects like functions. To access elements in a list you have to use square brackets instead.

Error ‘list’ object is not callable with a List Comprehension

When working with list comprehensions you might have also seen the “object is not callable” error.

This is a potential scenario when this could happen.

I have created a list of lists variable called matrix and I want to double every number in the matrix.

>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [[2*row(index) for index in range(len(row))] for row in matrix]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
  File "<stdin>", line 1, in <listcomp>
TypeError: 'list' object is not callable

This error is more difficult to spot when working with list comprehensions as opposed as when working with lists.

That’s because a list comprehension is written on a single line and includes multiple parentheses and square brackets.

If you look at the code closely you will notice that the issue is caused by the fact that in row(index) we are using parentheses instead of square brackets.

This is the correct code:

>>> [[2*row[index] for index in range(len(row))] for row in matrix]
[[2, 4, 6], [8, 10, 12], [14, 16, 18]]

Conclusion

Now that we went through few scenarios in which the errorobject is not callable can occur you should be able to fix it quickly if it occurs in your programs.

I hope this article has helped you save some time! 🙂

Related posts:

I’m a Tech Lead, Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

If you are working with lists in Python, a very common operation is accessing an element from the list. You can do this by using the index of the required element. In that case, the name of the list and the index has to be specified. 

For example, print (name_list[2]) will print the third element of the list called name_list. You need to use square brackets to mention the index number. But in case you use parenthesis for indexes, you will encounter an error “TypeError ‘list’ object is not callable in Python”.

We will look at the way to fix this error.       

Error: TypeError ‘list’ object is not callable in Python

This is a common programming error in Python which makes every programmer as a novice programmer. This type of error occurs when you try to access an element of a list using parenthesis “()”.

As we all know that python take parenthesis “()” to run a function, but when you try to access the value of list using parenthesis “()“ instead of using brackets  “ [] “ then python compiler generates the Error: “TypeError: ‘list’ object is not callable”

TypeError 'list' object is not callable in Python

Example:

# Inilised a list
list1 = ['Hi', 'This', 'is','STechies']

# Inilised variable i as 0
i = 0

# Inilised empty string
string1 = ''

# Run While loop to list length
while i < len(list1):
  # Joint each value of list to final string
  string1 = string1 + ' ' + list1(i)
  i += 1

# Print final Output
print(string1)

Output:

Traceback (most recent call last):
  File "str.py", line 7, in <module>
    string1 = string1 + ' ' + list1(i)
TypeError: 'list' object is not callable

In the above example, we are trying to access an element of a list using parenthesis “list1(i)” instead of brackets “list1[i]”

Due to which Python compiler try to run list1(i) as a function and generates an error: “TypeError: ‘list’ object is not callable”

How to resolve TypeError: ‘list’ object is not callable

To resolve this error, you need to use brackets “list1[i]» instead of parenthesis “list1(i)” to access an element of the list as shown in the example below:  

Correct Example:

# Initialised a list
list1 = ['Hi', 'This', 'is','STechies']

# Inilised variable i as 0
i = 0

# Inilised empty string
string1 = ''

# Run While loop to list length
while i < len(list1):
  # Joint each value of list to final string
  string1 = string1 + ' ' + list1[i]
  i += 1

# Print final Output
print(string1)

Output:

Hi This is STechies

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!

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

Reza Lavarian

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

Понравилась статья? Поделить с друзьями:
  • List object has no attribute replace как исправить
  • List object cannot be interpreted as an integer как исправить
  • List is empty egov mobile ошибка
  • List indices must be integers or slices not str как исправить
  • List indices must be integers or slices not str python ошибка