Python Set difference_update
Now, we are going to learn about the difference_update method. Well, we are quite familiar with the concept of the difference of the sets, and the difference method. In the difference method, we simply calculate the difference of the set.
Let’s quickly understand what we mean by the difference in the set. Let’s say that we have two sets set1 and set2, so the set1.difference(set2) is going to return a new set, which contains the elements, which are there in the set1, but not in the set2, which simply means that the new set contains elements which are unique to set1.
Python Set difference_update() Method
So, the difference_update method does the same thing. But if we are doing set1.difference_update(set2), then we are not going to get a new set, instead, the updates will be made to set1 itself. So, this method is not going to return a new set, but the changes will be made on set1 in the above case. We can also say that doing a set1.difference_update(set2), will simply remove all the elements from set1, which are also there in set2.
Let’s have a look at the below program, which tries to demonstrate the same thing.
As you can see in the above program, we have two sets, set1, and set2. Then we are trying to use the method difference_update. Since we are doing set1.difference_update(set2), the changes would be made to set1, and we can say that all the elements in set2, will be removed from set1. After that, we are printing set1, so let’s have a look at the output as well.
{29, 87, 31}
As you can see, we have set1 as output, and all the elements that are there in set2 were removed from set1. In this way, you can make use of the difference_update method as and when required in the program. Remember that here, we are not going to get a new set, but the changes will be made to set1 if we are doing set1.difference_update(set2).