Python Set intersection example

Python Set intersection example :

Intersection is used to find out the common elements between two Sets. Symbol ‘∩’ is used to denote intersection.
For example :

python set intersection

In the above example, we have two Set A and B and we are finding out the intersection between them A∩B. The intersection is the common elements between A and B.
From the above example, it is clear that A∩B = B∩C.

Finding intersection in Python :

Python comes with an inbuilt method intersection() to find out the intersection between two or more sets. In this blog post, we will show you how to use intersection() to find out the intersection between multiple sets in python. The syntax of the intersection() method is as below :

s.intersection(*t)

It will find the intersection between set s and one or multiple sets. It returns the final set.

Example :

Let’s try to implement it with an example (You can find the source code on Github ) :

python set intersection

As you can see, the first two times we have to find out the intersection between two sets but last time we have calculated the intersection between three sets.

python set intersection

Conclusion :

intersection() is really a useful method to find out the intersection between sets in python. Try to implement the example we have shown above and drop one comment below if you have any queries.

You might also like :

Leave a Reply