List object is not callable 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:\Personal\IJS\Code\main.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:\Personal\IJS\Code\tempCodeRunnerFile.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.

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

Если вы работаете со списками в 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. Не забудьте внимательно просмотреть свой код, чтобы выявить и исправить любые синтаксические ошибки и всегда использовать правильный синтаксис при работе со списками.

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') 

[Fixed] io.unsupportedoperation: not Writable in Python

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

  • [Solved] typeerror: unsupported format string passed to list.__format__

    [Solved] typeerror: unsupported format string passed to list.__format__

    May 31, 2023

  • Solving ‘Remote End Closed Connection’ in Python!

    Solving ‘Remote End Closed Connection’ in Python!

    by Namrata GulatiMay 31, 2023

  • [Fixed] io.unsupportedoperation: not Writable in Python

    [Fixed] io.unsupportedoperation: not Writable in Python

    by Namrata GulatiMay 31, 2023

  • [Fixing] Invalid ISOformat Strings in Python!

    [Fixing] Invalid ISOformat Strings in Python!

    by Namrata GulatiMay 31, 2023

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?

Suppose you have code such as the following:

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

for number in list:
    if number in myrange:
        print(number, 'is between 1 and 10')

Running the above code produces the following error:

Traceback (most recent call last):
  File "python", line 2, in <module>
TypeError: 'list' object is not callable

If you are getting a similar error such as the one above saying an «object is not callable», chances are you used a builtin name as a variable in your code. In this case and other cases 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.

Понравилась статья? Поделить с друзьями:
  • Libjcc dll дело ошибка
  • Lisp ошибка лишняя закрывающая скобка на входе
  • Lmu83 ошибка bc
  • Lirika saeco кофемашина выдает ошибку
  • Lms api ошибка