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

I cannot understand why this code does not work.

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

*argsused in python to unpack a list. I expected the above operation to create a set, but that is not the case. Can * args and ** kwargs in Python be used only to pass arguments as functions?

I am aware of a function set(), but curious why this syntax does not work.

+4
source share
2 answers

Thanks to PEP0448 it works these days, but you will need to upgrade to 3.5:

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

However, set(my_list)this is an obvious way to convert a list to a set, and therefore it should be used.

+6

set list

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

*args, , , .. .

- *args Python 3.5.

0

All Articles