How to create a set?
Now, while we are going to learn about the set in python, we need to understand how to create a set in python, or what are the different ways to create a set in python. Basically, we can create a set, by putting all the items within the curly brackets. (Remember that if the curly brackets are left empty, it would be a dictionary). So, Let’s have a look at a simple program, which demonstrates creating a set.
As you can see in the above program, we have created a set, where we have some elements within the curly brackets, and then we are checking the type of object that we have created. Also, after that, we are printing the set. Let’s have a look at the output of the above program.
How To Create A Set In Python
<class ‘set’>
{23, 87, 455, 12, 29, ‘GyaniPandit’}
As you can see, we have an object of the set, and then we are printing the set. If you have a close look at the set which is printed, you can see that the elements are not in the same order, as specified in the set. So, simply we can say that we have created a set now.
There is another way to create a set, which is using the set constructor. Let’s have a look at how we can make use of the set constructor, to create a set.
As you can see, in the above program, we have used the set constructor to create a set in our program. We are checking the type of the object, and also, we are printing the set. Let’s have a look at the output of the program now.
<class ‘set’>
set()
As you can see, we have the object of type set, and also, we have got an empty set here. To the set constructor, we can also provide some iterable. So, Let’s have a look at another program, which tries to demonstrate giving an iterable, to the set constructor.
As you can see, in the above program, we have provided some iterable to the set constructor here, and we are trying to print the set. Basically, we have mentioned earlier, that the set only contains unique elements, and duplicate elements are not allowed. Since our list contains duplicate elements in the above example, the duplicate elements won’t be again added to the set. Let’s have a look at the output now.
{34, 4, 11, 23, 29, 31}
As you can see, we have our set, which contains the values from that given list. In this way, we can create a set out of some iterable, using the set constructor. So, we have seen how we can create a set, by putting some elements in the curly brackets, and also using the set constructor. Also, if you want to create an empty set, you cannot do it with only empty curly brackets, since they would be considered as a dictionary. So, we need to make use of the set constructor.