Python Set difference
Now, we are going to have a look at the difference method. With the difference method, we get the difference of the two or more sets (we can also provide some other iterable as an argument to the method). Basically, Let’s understand what is difference first. Let’s consider that we have set1 and set2. Now, if we do set1.difference(set2), then we are going to get a new set, in which, we would have the elements that are there in set1, but not in set2. In other words, we get the elements that are unique to set1.
Let’s have a look at a simple program, which demonstrates using difference methods.
Python Set difference method
As you can see in the above program, we have two sets, set1, and set2. The set1 has some odd numbers. On the other hand, set2 has some prime numbers. Then, we are doing set1.difference(set2). Basically, with this, we get a new set, which contains the elements which are in set1, but not in set2. In short, we get the elements in the new set, which are unique to the set1.
If you try to execute the above program, the output of the above program comes out to be something like this –
{1, 9}
As you can see, we get a set, which contains the elements, which are unique to set1. In this way, we can make use of the difference method in our python programs, as and when required.