How to solve list object is not callable error in Python
In this tutorial, we will learn how to solve the TypeError: ‘list’ object is not callable in Python.
This error occurs for one of the following reasons:
-
If you try to use a
list
keyword as a variable name. -
Using the parenthesis
()
instead of square brackets[]
to access the elements from the list at a specific index.
Here is an example of how the error occurs:
price_list = [10, 20, 30]
# using parenthesis for accessing data
print(price_list(1))
Output:
Traceback (most recent call last):
File "main.py", line 13, in <module>
print(price_list(1))
TypeError: 'list' object is not callable
In the above example , we are getting the error because we are using the ()
to access the data from a list instead of []
square brackets.
To solve the “TypeError: ‘list’ object is not callable” error, use the square brackets []
syntax to access the elements from a list.
Here is an example:
price_list = [10, 20, 30]
print(price_list[1]) # 20
print(price_list[2]) # 30
Note: The list is an object data type in Python.
Another common cause of the error is using the built-in list()
function as a variable name in Python.
Here is an example:
# overiding the built-in list() function
list = [10, 20, 30]
# creating a list using list() function
fruits_list = list(['apple', 'banana', 'cherry'])
print(fruits_list)
Output:
Traceback (most recent call last):
File "main.py", line 14, in <module>
fruits_list = list(['apple', 'banana', 'cherry'])
TypeError: 'list' object is not callable
To Solve the error, change the variable name to someother and re-run the code.
# not overiding the built-in list() function
price_list = [10, 20, 30]
fruits_list = list(['apple', 'banana', 'cherry'])
print(fruits_list)
and do not use the list
keyword as a variable name because it is reserved for list()
function in python
Conclusion
The “list” object is not callable error occurs, when we try to call a list object as a python function using the parenthesis ()
. To solve the error, use the square brackets []
to access the data at a specific index eg: price_list[1]
and do not use the list
built-in keyword as a variable name because it is reserved for list()
function in python.