Python Set intersection() method
Python Set intersection() method
The set.intersection() method in Python returns a new set with elements that are similar between two or more sets.
Syntax
set.intersection(set1, set2 ... etc)
Parameter
set1- This parameter represents the set to search for equal items.
set2(optional)- This argument signifies the other set to search for equal items. One can compare as many sets as needed, only need to separate the sets with a comma.
Return
This method returns a new set with elements that are common to all sets.
Example 1
# Python program explaining
# the set.intersection() method
# initializing set1
set1 = {"a", "b", "c"}
print("Set 1:",set1)
# initializing set2
set2 = {"a", "z", "e"}
print("Set 2:",set2)
# initializing set3
set3 = {"a", "g", "m"}
print("Set 3:",set3)
# returning a set that contains similarity between the given three sets.
Intersection = set1.intersection(set2, set3)
# printing the result
print("Intersection value:",Intersection)
Output
Set 1: {'b', 'c', 'a'}
Set 2: {'e', 'z', 'a'}
Set 3: {'g', 'm', 'a'}
Intersection value: {'a'}
Example 2
# Python program explaining
# the set.intersection() method
# initializing first set
A = {"a", "e", "i"}
# initializing second set
B = {"o", "u","a"}
# initializing third set
C = {"u", "z", "a","m"}
# initializing fourth set
D = {"f","h","l","h","m"}
# searching common elements between Set A and Set B
print("Intersection between A and B(A ? B): ",A.intersection(B))
# searching common elements between Set B and Set C
print("Intersection between B and C(B ? C) : ",B.intersection(C))
# searching common elements between Set C and Set D
print("Intersection between C and D(C ? D) : ",C.intersection(D))
# searching common elements among Set A, Set B, Set C, Set D
print("Intersection between A, B, C and D(A ? B ? C ? D ) : ",A.intersection(B, C, D))
Output
Intersection between A and B(A ? B): {'a'}
Intersection between B and C(B ? C) : {'a', 'u'}
Intersection between C and D(C ? D) : {'m'}
Intersection between A, B, C and D(A ? B ? C ? D ) : set()
