Create a set from a list using {}

2019-07-07 18:47发布

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()?

3条回答
倾城 Initia
2楼-- · 2019-07-07 19:17

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:

{item for item in iterable}

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.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-07-07 19:31

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

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

It won't work on Python 2 (that was my question)

查看更多
疯言疯语
4楼-- · 2019-07-07 19:34

You can use

>>> ls = [1,2,3]
>>> {i for i in ls}
{1,2,3}
查看更多
登录 后发表回答