Skip to content Skip to sidebar Skip to footer

Create A Set From A List Using {}

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} Toda

Solution 1:

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.

Solution 2:

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)

Solution 3:

You can use

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

Post a Comment for "Create A Set From A List Using {}"