Python Set intersection_update

Now, we are going to learn about the intersection_udpate method. First of all, Let’s recall the intersection operation, which mostly we are familiar with. Let’s consider that there are two sets, set1, and set2. So, if we do set1.intersection(set2), then we get a new set, which is an intersection of the two sets. By intersection, we mean that the new set is going to contain the elements that are common to all the sets. But remember that with the intersection method, we are getting a new set.

## Python Set intersection_update() Method

Now, we are going to explore the intersection_update method, with which, we do not get a new set, but instead, the changes are made to the set on which the method is called. Let’s have a look at the below example, which demonstrates the intersection_update method.

As you can see in the above program, we have two sets, set1, and set2. Then we are trying to find the intersection of the two sets. This time, we are using the intersection_update method, due to which, the updates are made to the set, on which the method is called (set with reference variable set1). In the last instruction, we are printing set1. So, Let’s have a look at the output in our case.

{‘X’, ‘Y’}

As you can see, since we are trying to get the intersection, we got those elements into the set, which are common to all the sets. The changes were made to the set1. So, as and when required, we can also make use of the intersection_update method in our python programs.

So, this was about the set in python. We can make use of the set in our python programs, as and when required. Remember that the set can have only unique values, and we have seen some different operations that can be done on the sets here. You can practice some more programs related to sets so that you can get familiar with the concept of sets.