Open In App
Related Articles

Multiple Sets Intersection in Python

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In this article, a List of sets is given our task is to write a program to perform their intersection using Python.

Examples of finding the intersection of multiple sets

Input : test_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 3}]
Output : {3, 5}
Explanation : 3 and 5 is present in all the sets.

Method 1: Using a Logical operator

This is the simplest method to get the intersection of multiple sets using the Python logical operator

Python3

set_1 = {21, 10, 5, 11, 12}
set_2 = {5, 21, 3, 8, 9}
set_3 = {1, 21, 5, 3, 4, 5}
  
# getting all sets intersection using & operator
set4 = set1 & set2 & set3
  
print(set4)

                    

Output:

{21, 5}

Method 2: Using intersection() + * operator

In this, we will perform tasks to get intersections using intersection() and the * operator is used to pack all the sets together.

Python3

# initializing list
test_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 3}]
  
# printing original list
print("The original list is : " + str(test_list))
  
# getting all sets intersection using intersection()
res = set.intersection(*test_list)
  
# printing result
print("Intersected Sets : " + str(res))

                    

Output:

The original list is : [{3, 5, 6, 7}, {1, 2, 3, 5}, {8, 3, 5, 7}, {8, 3, 4, 5}]
Intersected Sets : {3, 5}

Method 3: Using reduce() + and_ operator

In this, we will perform intersection using and_ operator and Python reduce() does the task of getting all the sets packed together for the required operation.

Python3

from operator import and_
from functools import reduce
  
# initializing list
test_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 3}]
  
# printing original list
print("The original list is : " + str(test_list))
  
# getting all sets intersection using and_ operator
res = set(reduce(and_, test_list))
  
# printing result
print("Intersected Sets : " + str(res))

                    

Output:

The original list is : [{3, 5, 6, 7}, {1, 2, 3, 5}, {8, 3, 5, 7}, {8, 3, 4, 5}]
Intersected Sets : {3, 5}


Last Updated : 24 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads