Python Set intersection() Method with many examples

Python Set Intersection

Now, we are going to learn about the intersection method. Basically, if you are familiar with the set intersection operation, then it would be very easy to get this method. But anyways, we would consider this method from the basics, so that you can follow it on the go.

Let’s say that we have set1 and set2. So, if we do set1.intersection(set2), then we get a new set, which contains the elements, which are in both, set1 and set2. Let’s have a look at a simple example, which demonstrates the same thing.

Python Set intersection() Method

As you can see in the above program, we have two sets, set1, and set2, which have some elements. We are trying to do set1.intersection(set2). Doing this simply gets us a new set, which has the elements that are in both sets. Let’s have a look at the output of the above program.

{3, 5, 7, 11, 13}

As you can see in the output, we got the set, which has the elements, which are there in both sets. So, at times, when we are required to perform the intersection operation on two or more sets(or there can be some other iterables as well, as arguments to the method), we can make use of the intersection method in our python program.

Alternatively, we can also make use of the & operator, to find the intersection of sets. Let’s have a look at that as well.

As you can see in the above program, we are trying to perform the intersection of two sets using the & operator. If you try to execute the program and observe the output, you are going to get the same set as the previous output. You can have multiple sets here as well.