Multiple Sets Intersection in Python
Last Updated :
24 Mar, 2023
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 }
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
test_list = [{ 5 , 3 , 6 , 7 }, { 1 , 3 , 5 , 2 }, { 7 , 3 , 8 , 5 }, { 8 , 4 , 5 , 3 }]
print ( "The original list is : " + str (test_list))
res = set .intersection( * test_list)
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
test_list = [{ 5 , 3 , 6 , 7 }, { 1 , 3 , 5 , 2 }, { 7 , 3 , 8 , 5 }, { 8 , 4 , 5 , 3 }]
print ( "The original list is : " + str (test_list))
res = set ( reduce (and_, test_list))
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}
Please Login to comment...