Python set to list

后端 未结 7 1903
谎友^
谎友^ 2020-12-22 18:28

How can I convert a set to a list in Python? Using

a = set([\"Blah\", \"Hello\"])
a = list(a)

doesn\'t work. It gives me:

         


        
7条回答
  •  遥遥无期
    2020-12-22 19:10

    You've shadowed the builtin set by accidentally using it as a variable name, here is a simple way to replicate your error

    >>> set=set()
    >>> set=set()
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: 'set' object is not callable
    

    The first line rebinds set to an instance of set. The second line is trying to call the instance which of course fails.

    Here is a less confusing version using different names for each variable. Using a fresh interpreter

    >>> a=set()
    >>> b=a()
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: 'set' object is not callable
    

    Hopefully it is obvious that calling a is an error

提交回复
热议问题