A Python Set can be used for different Python Set Operations. There are different operation types used with python sets. In this Python lesson, we will focus on these operations and we will learn how to use them. We will see when we can use these Python Set Operations in our codes.
So what are these operations and operators used with them. These are:
The first operator used with Python sets is “|” operator. With this operator, we combine two sets together. We can do the same job with also python union method.
Below, we will combine two numbers set with the help of “|” operator.
The output of this code will be:
The same code can be written with python union method like below:
You can also watch the video of this lesson.
Again, we can use this operator to combine string sets like beloew:
As the output, we will see the combination of these sets. As you can see below, the double items will be only once in the new set. In other words, “Thorin” will be only one time in this new set.
The other operator used with Python sets is “&” operator. With this operator, we can find the common items in two sets together. We can do the same job with also python intersection method.
The output of this python code will be like beloe because, the common items in both sets are 2 and 3.
The below strin set example will be give also the common item of the sets.
“-“ operator is used to find the difference of two sets with if it is used with sets. The same job is done with difference method used in python. For example if we would like to find the items only in set1 but not in set2, we use (set1-set2) code. Let’s given an example to understand better.
In this python code, we have get the difference of two sets. The output of this code shows that the items reside in numbers2 but not in numbers1. So, the common items has removed in the new set.
We can do the similar thing with difference method also.
If we use numbers1-numbers2, this time the outputput will be different. And the usage of difference method will be also changed.
^ Operator is used to find the symmetric difference of two sets. Fort he same job, we can use symmetric_difference method of python. So what is symmetric difference? Symettric difference gives us the combinateion of the items in both set that are not common in these sets. In other words, it returns with the items that are not reside in both sets at the same time.
In the below, example, we will use ^ Operator and print the items that are not common in both of the sets.
As you can see below, the output of this code will give us the items that are not common in both sets.
We can do the same job by using symmetric_difference method.
The below usage will also give the same result. But the items in the set can be in different order.