Create a collection from the list using {}

Sometimes I have a list and I want to do some things with it. I 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 collection directly {1,2,3}, and it seems like an equivalent way to define it.

Then I wondered if I could use this syntax to create a set from this list.

{list}fails because it tries to create a collection with only one element - a list. And the lists resolve.

>>> mylist = [1,2,3]
>>> {mylist}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

So, interestingly: is there a way to create a collection from a list using the syntax {}instead set()?

+2
source share
3 answers

: Python Set: my_set = {* my_list} ?. , Python 3.5

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

Python 2 ( )

+2

( vs function). {} python - (, ), , .

, {} , , :

{item for item in iterable}

, python, . , , - set().

+4

you can use

>>> ls = [1,2,3]
>>> {i for i in ls}
{1,2,3}
+1
source

All Articles