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

允我心安 提交于 2019-12-10 17:05:19

问题


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.



来源:https://stackoverflow.com/questions/36199066/python-set-why-is-my-set-my-list-invalid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!