Python set intersection with examples

The intersection (A∩B) of two sets A and B is the set that contains all the elements common between both the sets.

We can perform an intersection between multiple sets too. Following image shows the set intersection example between two sets and three sets.

Set Intersection

 

Set Intersection

Python set intersection

In Python, we can use set class intersection() function to get the intersection of two sets.

Let’s look at an example of the intersection between two sets.

Output:

 

Python Two Sets Intersection

The intersection() function takes multiple set arguments too. Let’s look at another example of the intersection between multiple sets.

Output: {'a'}

Python Multiple Set Intersection

 

Python Multiple Set Intersection

Set intersection without arguments

We can call intersection() function without an argument too. In this case, a copy of the set will be returned.

Let’s see if the returned copy refers to the same set or a different one.

Output:

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: