Table of Contents
Hide
- Python TypeError: ‘list’ object is not callable
- Scenario 1 – Using the built-in name list as a variable name
- Solution for using the built-in name list as a variable name
- Scenario 2 – Indexing list using parenthesis()
- Solution for Indexing list using parenthesis()
- 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
- If you try to access elements of the list using parenthesis instead of square brackets
- 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.
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!
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.
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
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.
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
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.
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
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.
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
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
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
Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.
✋ 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:
- Declaring a variable with a name that’s also the name of a function
- Indexing a list by parenthesis rather than square brackets
- Calling a method that’s also the name of a property
- 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:
- Rename the variable
list
- 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
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”
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
I am trying to run this code where I have a list of lists. I need to add to inner lists, but I get the error
TypeError: 'list' object is not callable.
Can anyone tell me what am I doing wrong here.
def createlists():
global maxchar
global minchar
global worddict
global wordlists
for i in range(minchar, maxchar + 1):
wordlists.insert(i, list())
#add data to list now
for words in worddict.keys():
print words
print wordlists(len(words)) # <--- Error here.
(wordlists(len(words))).append(words) # <-- Error here too
print "adding word " + words + " at " + str(wordlists(len(words)))
print wordlists(5)
Bhargav Rao
48.7k28 gold badges124 silver badges139 bronze badges
asked Apr 20, 2011 at 19:52
For accessing the elements of a list you need to use the square brackets ([]
) and not the parenthesis (()
).
Instead of:
print wordlists(len(words))
you need to use:
print worldlists[len(words)]
And instead of:
(wordlists(len(words))).append(words)
you need to use:
worldlists[len(words)].append(words)
Bhargav Rao
48.7k28 gold badges124 silver badges139 bronze badges
answered Apr 20, 2011 at 20:00
orlporlp
111k35 gold badges211 silver badges308 bronze badges
1
To get elements of a list you have to use list[i]
instead of list(i)
.
jotik
16.6k12 gold badges55 silver badges118 bronze badges
answered Apr 20, 2011 at 20:00
IkkeIkke
97.9k23 gold badges96 silver badges120 bronze badges
wordlists is not a function, it is a list. You need the bracket subscript
print wordlists[len(words)]
answered Apr 20, 2011 at 20:00
eat_a_lemoneat_a_lemon
3,14811 gold badges33 silver badges49 bronze badges
1
I also got the error when I called a function that had the same name as another variable that was classified as a list.
Once I sorted out the naming the error was resolved.
answered Jan 5, 2013 at 0:58
You are attempting to call wordlists
here:
print wordlists(len(words)) <--- Error here.
Try:
print wordlists[len(words)]
answered Apr 20, 2011 at 20:00
samplebiassamplebias
36.7k6 gold badges106 silver badges103 bronze badges
Try wordlists[len(words)]
. ()
is a function call. When you do wordlists(..)
, python thinks that you are calling a function called wordlists
which turns out to be a list
. Hence the error.
answered Apr 20, 2011 at 20:00
Rumple StiltskinRumple Stiltskin
9,1471 gold badge20 silver badges25 bronze badges
Check your file name in which you have saved your program. If the file name is wordlists
then you will get an error. Your filename should not be same as any of methods{functions} that you use in your program.
answered Sep 7, 2013 at 7:32
Vinod KumarVinod Kumar
4795 silver badges12 bronze badges
del list
above command worked for me
answered Jun 12, 2019 at 9:23
1
Even I got the same error, but I solved it, I had used many list in my work so I just restarted my kernel (meaning if you are using a notebook such as Jupyter or Google Colab you can just restart and again run all the cells, by doing this your problem will be solved and the error vanishes.
Thank you.
answered Jun 29, 2019 at 21:41
TanuTanu
213 bronze badges
I am trying to run this code where I have a list of lists. I need to add to inner lists, but I get the error
TypeError: 'list' object is not callable.
Can anyone tell me what am I doing wrong here.
def createlists():
global maxchar
global minchar
global worddict
global wordlists
for i in range(minchar, maxchar + 1):
wordlists.insert(i, list())
#add data to list now
for words in worddict.keys():
print words
print wordlists(len(words)) # <--- Error here.
(wordlists(len(words))).append(words) # <-- Error here too
print "adding word " + words + " at " + str(wordlists(len(words)))
print wordlists(5)
Bhargav Rao
48.7k28 gold badges124 silver badges139 bronze badges
asked Apr 20, 2011 at 19:52
For accessing the elements of a list you need to use the square brackets ([]
) and not the parenthesis (()
).
Instead of:
print wordlists(len(words))
you need to use:
print worldlists[len(words)]
And instead of:
(wordlists(len(words))).append(words)
you need to use:
worldlists[len(words)].append(words)
Bhargav Rao
48.7k28 gold badges124 silver badges139 bronze badges
answered Apr 20, 2011 at 20:00
orlporlp
111k35 gold badges211 silver badges308 bronze badges
1
To get elements of a list you have to use list[i]
instead of list(i)
.
jotik
16.6k12 gold badges55 silver badges118 bronze badges
answered Apr 20, 2011 at 20:00
IkkeIkke
97.9k23 gold badges96 silver badges120 bronze badges
wordlists is not a function, it is a list. You need the bracket subscript
print wordlists[len(words)]
answered Apr 20, 2011 at 20:00
eat_a_lemoneat_a_lemon
3,14811 gold badges33 silver badges49 bronze badges
1
I also got the error when I called a function that had the same name as another variable that was classified as a list.
Once I sorted out the naming the error was resolved.
answered Jan 5, 2013 at 0:58
You are attempting to call wordlists
here:
print wordlists(len(words)) <--- Error here.
Try:
print wordlists[len(words)]
answered Apr 20, 2011 at 20:00
samplebiassamplebias
36.7k6 gold badges106 silver badges103 bronze badges
Try wordlists[len(words)]
. ()
is a function call. When you do wordlists(..)
, python thinks that you are calling a function called wordlists
which turns out to be a list
. Hence the error.
answered Apr 20, 2011 at 20:00
Rumple StiltskinRumple Stiltskin
9,1471 gold badge20 silver badges25 bronze badges
Check your file name in which you have saved your program. If the file name is wordlists
then you will get an error. Your filename should not be same as any of methods{functions} that you use in your program.
answered Sep 7, 2013 at 7:32
Vinod KumarVinod Kumar
4795 silver badges12 bronze badges
del list
above command worked for me
answered Jun 12, 2019 at 9:23
1
Even I got the same error, but I solved it, I had used many list in my work so I just restarted my kernel (meaning if you are using a notebook such as Jupyter or Google Colab you can just restart and again run all the cells, by doing this your problem will be solved and the error vanishes.
Thank you.
answered Jun 29, 2019 at 21:41
TanuTanu
213 bronze badges
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.
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.
the correct way to access an individual element is-
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.
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.
In this tutorial, learn how to resolve the error showing TypeError: ‘list’ object is not callable’ in Python. The short answer is: use the square bracket ([]
) in place of the round bracket when the Python list is not callable.
This error shows that the object in Python programming is not callable. To make it callable, you have to understand carefully the examples given here. The first section of the example contains the callable error showing TypeError: ‘list’ object is not callable’. While the second section showing the solution for the error.
The output of the second section example contains no error in the output. So, let’s start writing the error output and the program without error. First, start with the error example showing the TypeError: ‘list’ object is not callable’.
Code with Error : TypeError: ‘list’ object is not callable’ in Python
Here, in this example, you have to use the for loop of Python to print each element of the list. Include the print statement after the for loop to print the items of the list in Python.
However, the code contains the round bracket when passing x
as an argument inside the print statement. This round bracket is not the correct way to print each element of a list in Python.
myList = [‘Ram’, ‘Shyam’, 10, ‘Bilal’, 13.2, ‘Feroz’]; for x in range(len(myList)): print(myList(x)) |
Output
The above example gives an error output with the error message that the Python list is not callable. Read the next section to find out how to resolve the error TypeError: ‘list’ object is not callable’ in Python.
How to Resolve The Error in Python list is not callable
To resolve the problem of the error in the Python code. You have passed the variable x
as the argument inside the square brackets.
But it should not appear as myList(0)
, myList(1)
in the output. The above example showing the callable error with this round bracket as given in the above section.
Because the list variable works the same as the array element. To print each element of the list variable of Python, you have to print the list as myList[0], myList[1]...myList[n]
. Below is the example of for loop which gives this type of result in the output without any error.
myList = [‘Ram’, ‘Shyam’, 10, ‘Bilal’, 13.2, ‘Feroz’]; for x in range(len(myList)): print(myList[x]) |
Output
Shyam
10
Bilal
13.2
Feroz
The output of the above example gives no error and print each element in a single line.
DOWNLOAD Free PYTHON CHEAT SHEET
You may also like to read
- Concatenate two list variables in Python
- How to Loop Over Python List Variable
- Loop through dictionary elements in Python
I hope you like this tutorial on how to resolve the error in Python.
References
- Stackoverflow Discussion to Resolve the Error
- Errorcodespro Tutorial on how to Resolve this TypeError