Python Set: why is my_set = {*my_list} invalid?

2019-06-28 06:45发布

问题:

I am unable to figure out why this code doesn't work

>>> my_list = [1,2,3,4,5]
>>> my_set = {*my_list}
   File "<stdin>", line 1
    my_set = {*my_list}
          ^
SyntaxError: invalid syntax

*args is used in python to unpack list. My expectation was that the above operation would create a set but it didn't. Can *args and **kwargs in Python be only used to pass arguments as function ?

I am aware of the set() function but curious why this syntax doesn't work.

回答1:

Thanks to PEP0448, these days it does work, but you'll have to upgrade to 3.5:

>>> my_list = [1,2,3,4,5]
>>> my_set = {*my_list}
>>> my_set
{1, 2, 3, 4, 5}

That said, set(my_list) is the obvious way to convert a list to a set, and so it's the way you should use.



回答2:

Following is a way to declare a set using a pre-defined list

my_list = [1,2,3,4,5]  
my_set = set(my_list)

You would use *args when you're not sure how many arguments might be passed to your function, i.e. it allows you pass an arbitrary number of arguments to your function.

In conclusion, yes - *args is only used in function header prior to Python version 3.5.