How to solve a callable error for dictionaries? [duplicate] - python

This question already has answers here:
Why does code like `str = str(...)` cause a TypeError, but only the second time?
(20 answers)
Closed last month.
I tried to use this code from a tutorial at the REPL:
example = list('easyhoss')
The tutorial says that example should become equal to a list ['e', 'a', 's', 'y', 'h', 'o', 's', 's']. But I got an error instead:
>>> example = list('easyhoss')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
Why did this happen?

Seems like you've shadowed the builtin name list, which points at a class, by the same name pointing at an instance of it. Here is an example:
>>> example = list('easyhoss') # here `list` refers to the builtin class
>>> list = list('abc') # we create a variable `list` referencing an instance of `list`
>>> example = list('easyhoss') # here `list` refers to the instance
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: 'list' object is not callable
I believe this is fairly obvious. Python stores object names (functions and classes are objects, too) in namespaces (which are implemented as dictionaries), hence you can rewrite pretty much any name in any scope. It won't show up as an error of some sort. As you might know, Python emphasizes that "special cases aren't special enough to break the rules". And there are two major rules behind the problem you've faced:
Namespaces. Python supports nested namespaces. Theoretically you can endlessly nest them. As I've already mentioned, they are basically dictionaries of names and references to corresponding objects. Any module you create gets its own "global" namespace, though in fact it's just a local namespace with respect to that particular module.
Scoping. When you reference a name, the Python runtime looks it up in the local namespace (with respect to the reference) and, if such name does not exist, it repeats the attempt in a higher-level namespace. This process continues until there are no higher namespaces left. In that case you get a NameError. Builtin functions and classes reside in a special high-order namespace __builtins__. If you declare a variable named list in your module's global namespace, the interpreter will never search for that name in a higher-level namespace (that is __builtins__). Similarly, suppose you create a variable var inside a function in your module, and another variable var in the module. Then, if you reference var inside the function, you will never get the global var, because there is a var in the local namespace - the interpreter has no need to search it elsewhere.
Here is a simple illustration.
>>> example = list("abc") # Works fine
>>>
>>> # Creating name "list" in the global namespace of the module
>>> list = list("abc")
>>>
>>> example = list("abc")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
>>> # Python looks for "list" and finds it in the global namespace,
>>> # but it's not the proper "list".
>>>
>>> # Let's remove "list" from the global namespace
>>> del list
>>> # Since there is no "list" in the global namespace of the module,
>>> # Python goes to a higher-level namespace to find the name.
>>> example = list("abc") # It works.
So, as you see there is nothing special about Python builtins. And your case is a mere example of universal rules. You'd better use an IDE (e.g. a free version of PyCharm, or Atom with Python plugins) that highlights name shadowing to avoid such errors.
You might as well be wondering what is a "callable", in which case you can read this post. list, being a class, is callable. Calling a class triggers instance construction and initialisation. An instance might as well be callable, but list instances are not. If you are even more puzzled by the distinction between classes and instances, then you might want to read the documentation (quite conveniently, the same page covers namespaces and scoping).
If you want to know more about builtins, please read the answer by Christian Dean.
P.S. When you start an interactive Python session, you create a temporary module.

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.

If you are in a interactive session and don't want to restart you can remove the shadowing with
del list

In the league of stupid Monday morning mistakes, using round brackets instead of square brackets when trying to access an item in the list will also give you the same error message:
l=[1,2,3]
print(l[2])#GOOD
print(l(2))#BAD
TypeError: 'list' object is not callable

You may have used built-in name 'list' for a variable in your code.
If you are using Jupyter notebook, sometimes even if you change the name of that variable from 'list' to something different and rerun that cell, you may still get the error. In this case you need to restart the Kernal.
In order to make sure that the name has change, click on the word 'list' when you are creating a list object and press Shift+Tab, and check if Docstring shows it as an empty list.

Why does TypeError: 'list' object is not callable appear?
Explanation:
It is because you defined list as a variable before (i am pretty sure), so it would be a list, not the function anymore, that's why everyone shouldn't name variables functions, the below is the same as what you're doing now:
>>> [1,2,3]()
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
[1,2,3]()
TypeError: 'list' object is not callable
>>>
So you need it to be the default function of list, how to detect if it is? just use:
>>> list
<class 'list'>
>>> list = [1,2,3]
>>> list
[1, 2, 3]
>>> list()
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
list()
TypeError: 'list' object is not callable
>>>
How do i detect whether a variable name is a function? well, just simple see if it has a different color, or use a code like:
>>> 'list' in dir(__builtins__)
True
>>> 'blah' in dir(__builtins__)
False
>>>
After this, you should know why does TypeError: 'list' object is not callable appear.
Okay, so now...
How to fix this TypeError: 'list' object is not callable error?
Code:
You have to either do __builtins__.list():
>>> list = [1,2,3]
>>> __builtins__.list()
[]
>>>
Or use []:
>>> list = [1,2,3]
>>> []
[]
>>>
Or remove list variable from memory:
>>> list = [1,2,3]
>>> del list
>>> list()
[]
>>>
Or just rename the variable:
>>> lst = [1,2,3]
>>> list()
[]
>>>
P.S. Last one is the most preferable i guess :-)
There are a whole bunch of solutions that work.
References:
'id' is a bad variable name in Python
How do I use a keyword as a variable name?
How to use reserved keyword as the name of variable in python?

find out what you have assigned to 'list' by displaying it
>>> print(list)
if it has content, you have to clean it with
>>> del list
now display 'list' again and expect this
<class 'list'>
Once you see this, you can proceed with your copy.

For me it was a flask server returning some videos array (which I expected to be in json format..)
adding json.dumps(videos) fixed this issue

I was getting this error for another reason:
I accidentally had a blank list created in my __init__ which had the same name as a method I was trying to call (I had just finished refactoring a bit and the variable was no longer needed, but I missed it when cleaning up). So when I was instantiating the class and trying to call the method, it thought I was referencing the list object, not the method:
class DumbMistake:
def __init__(self, k, v):
self.k = k
self.v = v
self.update = []
def update(self):
// do updates to k, v, etc
if __name__ == '__main__':
DumbMistake().update('one,two,three', '1,2,3')
So it was trying to assign the two strings to self.update[] instead of calling the update() method. Removed the variable and it all worked as intended. Hope this helps someone.

You have already assigned a value to list.
So, you cannot use the list() when it’s a variable.
Restart the shell or IDE, by pressing Ctrl+F6 on your computer.
Hope this works too.

I found myself getting this error because I had a method that returned a list that I gave a #property decorator. I forgot about the decorator and was calling method() instead of just method which gave this same error.

Why error occurred?
Because you have named any of your list as "list" in current kernel.
example:
import operator
list = [1, 4, 5, 7, 9, 11]
#you are naming list as "list"
print("The sum is : ", end="")
print(list(itertools.accumulate(list1)))
print("The product is : ", end="")
print(list(itertools.accumulate(list1, operator.mul)))
Solution:
Simply restart the kernel.

Close the current interpreter using exit() command and reopen typing python to start your work. And do not name a list as list literally. Then you will be fine.

to solve the error like this one: "list object is not callable in python" even you are changing the variable name then please restart the kernel in Python Jutyter Notebook if you are using it or simply restart the IDE.
I hope this will work. Thank you!!!

Related

Python Dictionary scores [duplicate]

Given the following integers and calculation
from __future__ import division
a = 23
b = 45
c = 16
round((a/b)*0.9*c)
This results in:
TypeError: 'int' object is not callable.
How can I round the output to an integer?
Somewhere else in your code you have something that looks like this:
round = 42
Then when you write
round((a/b)*0.9*c)
that is interpreted as meaning a function call on the object bound to round, which is an int. And that fails.
The problem is whatever code binds an int to the name round. Find that and remove it.
I got the same error (TypeError: 'int' object is not callable)
def xlim(i,k,s1,s2):
x=i/(2*k)
xl=x*(1-s2*x-s1*(1-x)) / (1-s2*x**2-2*s1*x(1-x))
return xl
... ... ... ...
>>> xlim(1,100,0,0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in xlim
TypeError: 'int' object is not callable
after reading this post I realized that I forgot a multiplication sign * so
def xlim(i,k,s1,s2):
x=i/(2*k)
xl=x*(1-s2*x-s1*(1-x)) / (1-s2*x**2-2*s1*x * (1-x))
return xl
xlim(1.0,100.0,0.0,0.0)
0.005
tanks
Stop stomping on round somewhere else by binding an int to it.
I was also facing this issue but in a little different scenario.
Scenario:
param = 1
def param():
.....
def func():
if param:
var = {passing a dict here}
param(var)
It looks simple and a stupid mistake here, but due to multiple lines of codes in the actual code, it took some time for me to figure out that the variable name I was using was same as my function name because of which I was getting this error.
Changed function name to something else and it worked.
So, basically, according to what I understood, this error means that you are trying to use an integer as a function or in more simple terms, the called function name is also used as an integer somewhere in the code.
So, just try to find out all occurrences of the called function name and look if that is being used as an integer somewhere.
I struggled to find this, so, sharing it here so that someone else may save their time, in case if they get into this issue.
In my case I changed:
return <variable>
with:
return str(<variable>)
try with the following and it must work:
str(round((a/b)*0.9*c))
Sometimes the problem would be forgetting an operator while calculation.
Example:
print(n-(-1+(math.sqrt(1-4(2*(-n))))/2)) rather
it has to be
print(n-(-1+(math.sqrt(1-4*(2*(-n))))/2))
HTH
There are two reasons for this error "TypeError: 'int' object is not callable"
Function Has an Integer Value
Consider
a = [5, 10, 15, 20]
max = 0
max = max(a)
print(max)
This will produce TypeError: 'int' object is not callable.
Just change the variable name "max" to var(say).
a = [5, 10, 15, 20]
var = 0
var = max(a)
print(var)
The above code will run perfectly without any error!!
Missing a Mathematical Operator
Consider
a = 5
b = a(a+1)
print(b)
This will also produce TypeError: 'int' object is not callable.
You might have forgotten to put the operator in between ( '*' in this case )
As mentioned you might have a variable named round (of type int) in your code and removing that should get rid of the error. For Jupyter notebooks however, simply clearing a cell or deleting it might not take the variable out of scope. In such a case, you can restart your notebook to start afresh after deleting the variable.
You can always use the below method to disambiguate the function.
__import__('__builtin__').round((a/b)*0.9*c)
__builtin__ is the module name for all the built in functions like round, min, max etc. Use the appropriate module name for functions from other modules.
I encountered this error because I was calling a function inside my model that used the #property decorator.
#property
def volume_range(self):
return self.max_oz - self.min_oz
When I tried to call this method in my serializer, I hit the error "TypeError: 'int' object is not callable".
def get_oz_range(self, obj):
return obj.volume_range()
In short, the issue was that the #property decorator turns a function into a getter. You can read more about property() in this SO response.
The solution for me was to access volume_range like a variable and not call it as a function:
def get_oz_range(self, obj):
return obj.volume_range # No more parenthesis

TypeError: 'dict' object is not callable while creating an empty dictionary in Python2.7 [duplicate]

This question already has answers here:
Why does code like `str = str(...)` cause a TypeError, but only the second time?
(20 answers)
Closed last month.
I tried to use this code from a tutorial at the REPL:
example = list('easyhoss')
The tutorial says that example should become equal to a list ['e', 'a', 's', 'y', 'h', 'o', 's', 's']. But I got an error instead:
>>> example = list('easyhoss')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
Why did this happen?
Seems like you've shadowed the builtin name list, which points at a class, by the same name pointing at an instance of it. Here is an example:
>>> example = list('easyhoss') # here `list` refers to the builtin class
>>> list = list('abc') # we create a variable `list` referencing an instance of `list`
>>> example = list('easyhoss') # here `list` refers to the instance
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: 'list' object is not callable
I believe this is fairly obvious. Python stores object names (functions and classes are objects, too) in namespaces (which are implemented as dictionaries), hence you can rewrite pretty much any name in any scope. It won't show up as an error of some sort. As you might know, Python emphasizes that "special cases aren't special enough to break the rules". And there are two major rules behind the problem you've faced:
Namespaces. Python supports nested namespaces. Theoretically you can endlessly nest them. As I've already mentioned, they are basically dictionaries of names and references to corresponding objects. Any module you create gets its own "global" namespace, though in fact it's just a local namespace with respect to that particular module.
Scoping. When you reference a name, the Python runtime looks it up in the local namespace (with respect to the reference) and, if such name does not exist, it repeats the attempt in a higher-level namespace. This process continues until there are no higher namespaces left. In that case you get a NameError. Builtin functions and classes reside in a special high-order namespace __builtins__. If you declare a variable named list in your module's global namespace, the interpreter will never search for that name in a higher-level namespace (that is __builtins__). Similarly, suppose you create a variable var inside a function in your module, and another variable var in the module. Then, if you reference var inside the function, you will never get the global var, because there is a var in the local namespace - the interpreter has no need to search it elsewhere.
Here is a simple illustration.
>>> example = list("abc") # Works fine
>>>
>>> # Creating name "list" in the global namespace of the module
>>> list = list("abc")
>>>
>>> example = list("abc")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
>>> # Python looks for "list" and finds it in the global namespace,
>>> # but it's not the proper "list".
>>>
>>> # Let's remove "list" from the global namespace
>>> del list
>>> # Since there is no "list" in the global namespace of the module,
>>> # Python goes to a higher-level namespace to find the name.
>>> example = list("abc") # It works.
So, as you see there is nothing special about Python builtins. And your case is a mere example of universal rules. You'd better use an IDE (e.g. a free version of PyCharm, or Atom with Python plugins) that highlights name shadowing to avoid such errors.
You might as well be wondering what is a "callable", in which case you can read this post. list, being a class, is callable. Calling a class triggers instance construction and initialisation. An instance might as well be callable, but list instances are not. If you are even more puzzled by the distinction between classes and instances, then you might want to read the documentation (quite conveniently, the same page covers namespaces and scoping).
If you want to know more about builtins, please read the answer by Christian Dean.
P.S. When you start an interactive Python session, you create a temporary module.
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.
If you are in a interactive session and don't want to restart you can remove the shadowing with
del list
In the league of stupid Monday morning mistakes, using round brackets instead of square brackets when trying to access an item in the list will also give you the same error message:
l=[1,2,3]
print(l[2])#GOOD
print(l(2))#BAD
TypeError: 'list' object is not callable
You may have used built-in name 'list' for a variable in your code.
If you are using Jupyter notebook, sometimes even if you change the name of that variable from 'list' to something different and rerun that cell, you may still get the error. In this case you need to restart the Kernal.
In order to make sure that the name has change, click on the word 'list' when you are creating a list object and press Shift+Tab, and check if Docstring shows it as an empty list.
Why does TypeError: 'list' object is not callable appear?
Explanation:
It is because you defined list as a variable before (i am pretty sure), so it would be a list, not the function anymore, that's why everyone shouldn't name variables functions, the below is the same as what you're doing now:
>>> [1,2,3]()
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
[1,2,3]()
TypeError: 'list' object is not callable
>>>
So you need it to be the default function of list, how to detect if it is? just use:
>>> list
<class 'list'>
>>> list = [1,2,3]
>>> list
[1, 2, 3]
>>> list()
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
list()
TypeError: 'list' object is not callable
>>>
How do i detect whether a variable name is a function? well, just simple see if it has a different color, or use a code like:
>>> 'list' in dir(__builtins__)
True
>>> 'blah' in dir(__builtins__)
False
>>>
After this, you should know why does TypeError: 'list' object is not callable appear.
Okay, so now...
How to fix this TypeError: 'list' object is not callable error?
Code:
You have to either do __builtins__.list():
>>> list = [1,2,3]
>>> __builtins__.list()
[]
>>>
Or use []:
>>> list = [1,2,3]
>>> []
[]
>>>
Or remove list variable from memory:
>>> list = [1,2,3]
>>> del list
>>> list()
[]
>>>
Or just rename the variable:
>>> lst = [1,2,3]
>>> list()
[]
>>>
P.S. Last one is the most preferable i guess :-)
There are a whole bunch of solutions that work.
References:
'id' is a bad variable name in Python
How do I use a keyword as a variable name?
How to use reserved keyword as the name of variable in python?
find out what you have assigned to 'list' by displaying it
>>> print(list)
if it has content, you have to clean it with
>>> del list
now display 'list' again and expect this
<class 'list'>
Once you see this, you can proceed with your copy.
For me it was a flask server returning some videos array (which I expected to be in json format..)
adding json.dumps(videos) fixed this issue
I was getting this error for another reason:
I accidentally had a blank list created in my __init__ which had the same name as a method I was trying to call (I had just finished refactoring a bit and the variable was no longer needed, but I missed it when cleaning up). So when I was instantiating the class and trying to call the method, it thought I was referencing the list object, not the method:
class DumbMistake:
def __init__(self, k, v):
self.k = k
self.v = v
self.update = []
def update(self):
// do updates to k, v, etc
if __name__ == '__main__':
DumbMistake().update('one,two,three', '1,2,3')
So it was trying to assign the two strings to self.update[] instead of calling the update() method. Removed the variable and it all worked as intended. Hope this helps someone.
You have already assigned a value to list.
So, you cannot use the list() when it’s a variable.
Restart the shell or IDE, by pressing Ctrl+F6 on your computer.
Hope this works too.
I found myself getting this error because I had a method that returned a list that I gave a #property decorator. I forgot about the decorator and was calling method() instead of just method which gave this same error.
Why error occurred?
Because you have named any of your list as "list" in current kernel.
example:
import operator
list = [1, 4, 5, 7, 9, 11]
#you are naming list as "list"
print("The sum is : ", end="")
print(list(itertools.accumulate(list1)))
print("The product is : ", end="")
print(list(itertools.accumulate(list1, operator.mul)))
Solution:
Simply restart the kernel.
Close the current interpreter using exit() command and reopen typing python to start your work. And do not name a list as list literally. Then you will be fine.
to solve the error like this one: "list object is not callable in python" even you are changing the variable name then please restart the kernel in Python Jutyter Notebook if you are using it or simply restart the IDE.
I hope this will work. Thank you!!!

Python 3 unique entries in a list tried using set on list but object not callable [duplicate]

This question already has answers here:
Why does code like `str = str(...)` cause a TypeError, but only the second time?
(20 answers)
Closed last month.
I tried to use this code from a tutorial at the REPL:
example = list('easyhoss')
The tutorial says that example should become equal to a list ['e', 'a', 's', 'y', 'h', 'o', 's', 's']. But I got an error instead:
>>> example = list('easyhoss')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
Why did this happen?
Seems like you've shadowed the builtin name list, which points at a class, by the same name pointing at an instance of it. Here is an example:
>>> example = list('easyhoss') # here `list` refers to the builtin class
>>> list = list('abc') # we create a variable `list` referencing an instance of `list`
>>> example = list('easyhoss') # here `list` refers to the instance
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: 'list' object is not callable
I believe this is fairly obvious. Python stores object names (functions and classes are objects, too) in namespaces (which are implemented as dictionaries), hence you can rewrite pretty much any name in any scope. It won't show up as an error of some sort. As you might know, Python emphasizes that "special cases aren't special enough to break the rules". And there are two major rules behind the problem you've faced:
Namespaces. Python supports nested namespaces. Theoretically you can endlessly nest them. As I've already mentioned, they are basically dictionaries of names and references to corresponding objects. Any module you create gets its own "global" namespace, though in fact it's just a local namespace with respect to that particular module.
Scoping. When you reference a name, the Python runtime looks it up in the local namespace (with respect to the reference) and, if such name does not exist, it repeats the attempt in a higher-level namespace. This process continues until there are no higher namespaces left. In that case you get a NameError. Builtin functions and classes reside in a special high-order namespace __builtins__. If you declare a variable named list in your module's global namespace, the interpreter will never search for that name in a higher-level namespace (that is __builtins__). Similarly, suppose you create a variable var inside a function in your module, and another variable var in the module. Then, if you reference var inside the function, you will never get the global var, because there is a var in the local namespace - the interpreter has no need to search it elsewhere.
Here is a simple illustration.
>>> example = list("abc") # Works fine
>>>
>>> # Creating name "list" in the global namespace of the module
>>> list = list("abc")
>>>
>>> example = list("abc")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
>>> # Python looks for "list" and finds it in the global namespace,
>>> # but it's not the proper "list".
>>>
>>> # Let's remove "list" from the global namespace
>>> del list
>>> # Since there is no "list" in the global namespace of the module,
>>> # Python goes to a higher-level namespace to find the name.
>>> example = list("abc") # It works.
So, as you see there is nothing special about Python builtins. And your case is a mere example of universal rules. You'd better use an IDE (e.g. a free version of PyCharm, or Atom with Python plugins) that highlights name shadowing to avoid such errors.
You might as well be wondering what is a "callable", in which case you can read this post. list, being a class, is callable. Calling a class triggers instance construction and initialisation. An instance might as well be callable, but list instances are not. If you are even more puzzled by the distinction between classes and instances, then you might want to read the documentation (quite conveniently, the same page covers namespaces and scoping).
If you want to know more about builtins, please read the answer by Christian Dean.
P.S. When you start an interactive Python session, you create a temporary module.
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.
If you are in a interactive session and don't want to restart you can remove the shadowing with
del list
In the league of stupid Monday morning mistakes, using round brackets instead of square brackets when trying to access an item in the list will also give you the same error message:
l=[1,2,3]
print(l[2])#GOOD
print(l(2))#BAD
TypeError: 'list' object is not callable
You may have used built-in name 'list' for a variable in your code.
If you are using Jupyter notebook, sometimes even if you change the name of that variable from 'list' to something different and rerun that cell, you may still get the error. In this case you need to restart the Kernal.
In order to make sure that the name has change, click on the word 'list' when you are creating a list object and press Shift+Tab, and check if Docstring shows it as an empty list.
Why does TypeError: 'list' object is not callable appear?
Explanation:
It is because you defined list as a variable before (i am pretty sure), so it would be a list, not the function anymore, that's why everyone shouldn't name variables functions, the below is the same as what you're doing now:
>>> [1,2,3]()
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
[1,2,3]()
TypeError: 'list' object is not callable
>>>
So you need it to be the default function of list, how to detect if it is? just use:
>>> list
<class 'list'>
>>> list = [1,2,3]
>>> list
[1, 2, 3]
>>> list()
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
list()
TypeError: 'list' object is not callable
>>>
How do i detect whether a variable name is a function? well, just simple see if it has a different color, or use a code like:
>>> 'list' in dir(__builtins__)
True
>>> 'blah' in dir(__builtins__)
False
>>>
After this, you should know why does TypeError: 'list' object is not callable appear.
Okay, so now...
How to fix this TypeError: 'list' object is not callable error?
Code:
You have to either do __builtins__.list():
>>> list = [1,2,3]
>>> __builtins__.list()
[]
>>>
Or use []:
>>> list = [1,2,3]
>>> []
[]
>>>
Or remove list variable from memory:
>>> list = [1,2,3]
>>> del list
>>> list()
[]
>>>
Or just rename the variable:
>>> lst = [1,2,3]
>>> list()
[]
>>>
P.S. Last one is the most preferable i guess :-)
There are a whole bunch of solutions that work.
References:
'id' is a bad variable name in Python
How do I use a keyword as a variable name?
How to use reserved keyword as the name of variable in python?
find out what you have assigned to 'list' by displaying it
>>> print(list)
if it has content, you have to clean it with
>>> del list
now display 'list' again and expect this
<class 'list'>
Once you see this, you can proceed with your copy.
For me it was a flask server returning some videos array (which I expected to be in json format..)
adding json.dumps(videos) fixed this issue
I was getting this error for another reason:
I accidentally had a blank list created in my __init__ which had the same name as a method I was trying to call (I had just finished refactoring a bit and the variable was no longer needed, but I missed it when cleaning up). So when I was instantiating the class and trying to call the method, it thought I was referencing the list object, not the method:
class DumbMistake:
def __init__(self, k, v):
self.k = k
self.v = v
self.update = []
def update(self):
// do updates to k, v, etc
if __name__ == '__main__':
DumbMistake().update('one,two,three', '1,2,3')
So it was trying to assign the two strings to self.update[] instead of calling the update() method. Removed the variable and it all worked as intended. Hope this helps someone.
You have already assigned a value to list.
So, you cannot use the list() when it’s a variable.
Restart the shell or IDE, by pressing Ctrl+F6 on your computer.
Hope this works too.
I found myself getting this error because I had a method that returned a list that I gave a #property decorator. I forgot about the decorator and was calling method() instead of just method which gave this same error.
Why error occurred?
Because you have named any of your list as "list" in current kernel.
example:
import operator
list = [1, 4, 5, 7, 9, 11]
#you are naming list as "list"
print("The sum is : ", end="")
print(list(itertools.accumulate(list1)))
print("The product is : ", end="")
print(list(itertools.accumulate(list1, operator.mul)))
Solution:
Simply restart the kernel.
Close the current interpreter using exit() command and reopen typing python to start your work. And do not name a list as list literally. Then you will be fine.
to solve the error like this one: "list object is not callable in python" even you are changing the variable name then please restart the kernel in Python Jutyter Notebook if you are using it or simply restart the IDE.
I hope this will work. Thank you!!!

TypeError: 'list' object is not callable(python) [duplicate]

This question already has answers here:
Why does "example = list(...)" result in "TypeError: 'list' object is not callable"? [duplicate]
(14 answers)
Closed 3 years ago.
I have a simple script:
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')
However, whenever I attempt to run my script, Python raises an error:
Traceback (most recent call last):
File "python", line 2, in <module>
TypeError: 'list' object is not callable
What does this error mean? Why am I getting it? And how can I fix it?
Before you can fully understand what the error means and how to solve, it is important to understand what a built-in name is in Python.
What is a built-in name?
In Python, a built-in name is a name that the Python interpreter already has assigned a predefined value. The value can be either a function or class object. These names are always made available by default, no matter the scope. Some of the values assigned to these names represent fundamental types of the Python language, while others are simple useful.
As of the latest version of Python - 3.6.2 - there are currently 61 built-in names. A full list of the names and how they should be used, can be found in the documentation section Built-in Functions.
An important point to note however, is that Python will not stop you from re-assigning builtin names. Built-in names are not reserved, and Python allows them to be used as variable names as well.
Here is an example using the dict built-in:
>>> dict = {}
>>> dict
{}
>>>
As you can see, Python allowed us to assign the dict name, to reference a dictionary object.
What does "TypeError: 'list' object is not callable" mean?
To put it simply, the reason the error is occurring is because you re-assigned the builtin name list in the script:
list = [1, 2, 3, 4, 5]
When you did this, you overwrote the predefined value of the built-in name. This means you can no longer use the predefined value of list, which is a class object representing Python list.
Thus, when you tried to use the list class to create a new list from a range object:
myrange = list(range(1, 10))
Python raised an error. The reason the error says "'list' object is not callable", is because as said above, the name list was referring to a list object. So the above would be the equivalent of doing:
[1, 2, 3, 4, 5](range(1, 10))
Which of course makes no sense. You cannot call a list object.
How can I fix the error?
If you are getting a similar error such as this one saying an "object is not callable", chances are you used a builtin name as a variable in your code. In this case the fix is as simple as renaming the offending variable. For example, to fix the above code, we could rename our list variable to ints:
ints = [1, 2, 3, 4, 5] # Rename "list" to "ints"
myrange = list(range(1, 10))
for number in ints: # Renamed "list" to "ints"
if number in myrange:
print(number, 'is between 1 and 10')
PEP8 - the official Python style guide - includes many recommendations on naming variables.
This is a very common error new and old Python users make. This is why it's important to always avoid using built-in names as variables such as str, dict, list, range, etc.
Many linters and IDEs will warn you when you attempt to use a built-in name as a variable. If your frequently make this mistake, it may be worth your time to invest in one of these programs.
I didn't rename a built-in name, but I'm still getting "TypeError: 'list' object is not callable". What gives?
Another common cause for the above error is attempting to index a list using parenthesis (()) rather than square brackets ([]). For example:
>>> lst = [1, 2]
>>> lst(0)
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
lst(0)
TypeError: 'list' object is not callable
For an explanation of the full problem and what can be done to fix it, see TypeError: 'list' object is not callable while trying to access a list.
Here is the mcve!
>>> []()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
Try also {}() and ()(). The message TypeError: 'X' object is not callable means that you wrote expression(some_arguments) where expression is an instance of the X type, and this type doesn't support to be used in a function call syntax. Most of the time you wrote this because you thought expression was a function or some other callable type.

Does a variable override method here

I am starting to play around with python a little, and as a novice i tried this:
>>> s="";str=""
>>> for x in [ 1,2,3,4,5,6 ] :
... s += str(x)
...
Traceback (most recent call last):
File "<console>", line 3, in <module>
TypeError: 'str' object is not callable
I accidentally declared a variable called str (str is supposed to be a function).
Assuming it would break the semantics too much, even in a dynamically
typed language, is there a namespace i can use to qualify methods
like str and ensure this does not happen or make it difficult?
This is what import <module> instead of from <module> import * is used for. As long as you use str in the only meaning of local variable value in <module>, you can use
module.str elswhere, without mangling namespace.
The only tokens that can't be clashed are keywords. This is intended functionality and there is no way to prevent this: everything is an object in Python
You might want to use some IDE tools, p.ex. Eclipse+PyDev, that checks your code and warn for possible errors.
As per your question you have already defined str=""
so when you will call str method which converts values into string it will not call actual method in place of that it will call str="".
that's why you are getting error because you can not call a str object to convert int to string.

Categories