The intersection()
function in Python is a method of the Set data structure. It returns a new set that contains only the elements that are common to both the original set and the set provided as an argument to the function. This function helps to find the intersection of two sets, i.e., it returns a set that contains elements that are present in both sets.
Return Values
The intersection()
method returns a new set with the common elements.
How to Use intersection()
in Python
Example 1:
The intersection()
method returns a new set with elements that are common to all sets.
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5}
result = set1.intersection(set2, set3)
print(result)
Example 2:
The intersection()
method can be used with multiple sets.
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5}
set4 = {3, 5, 6}
result = set1.intersection(set2, set3, set4)
print(result)
Example 3:
The intersection()
method can also be used with the '&' operator.
set1 = {1, 2, 3}
set2 = {2, 3, 4}
result = set1 & set2
print(result)