Sometimes I have a list and I want to do some set actions with it. What I do is to write things like:
>>> mylist = [1,2,3]
>>> myset = set(mylist)
{1, 2, 3}
Today I discovered that from Python 2.7 you can also define a set by directly saying {1,2,3}
, and it appears to be an equivalent way to define it.
Then, I wondered if I can use this syntax to create a set from a given list.
{list}
fails because it tries to create a set with just one element, the list. And lists are unhashable.
>>> mylist = [1,2,3]
>>> {mylist}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
So, I wonder: is there any way to create a set out of a list using the {}
syntax instead of set()
?
Basically they are not equivalent (expression vs function). The main purpose of adding
{}
to python was because of set comprehension (like list comprehension) which you can also create a set using it by passing some hashable objects.So if you want to create a set using
{}
from an iterable you can use a set comprehension like following:Also note that empty braces represent a dictionary in python not a set. So if you want to just create an empty set the proper way is using
set()
function.I asked a related question recently: Python Set: why is my_set = {*my_list} invalid?. My question contains your answer if you are using Python 3.5
It won't work on Python 2 (that was my question)
You can use