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.
Thanks to PEP0448, these days it does work, but you'll have to upgrade to 3.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.Following is a way to declare a
set
using a pre-definedlist
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.