TypeError: 'list' object is not callable in python

前端 未结 11 1736
醉梦人生
醉梦人生 2020-11-22 13:11

I am novice to Python and following a tutorial. There is an example of list in the tutorial :

example = list(\'easyhoss\')

Now

11条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 14:02

    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 "", line 1, in 
        [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
    
    >>> list = [1,2,3]
    >>> list
    [1, 2, 3]
    >>> list()
    Traceback (most recent call last):
      File "", line 1, in 
        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?

提交回复
热议问题