Python set intersection
In this post, you will learn about the set interaction method of Python.
The set operation intersection takes only the elements that are in both sets. It contains the elements that the two sets have in common. The returned set contains only items that exist in both sets, or in all sets, if the comparison is done with more than two sets. Intersection of two given sets X and Y is a set which consists of all the elements which are common to both X and Y. It is denoted by ∩ symbol. The Set intersection with the elements that are common to Set X and Y is represented as -
X ∩ Y = Y ∩ X
The set.intersection() method of Python returns a set of elements which are common in the given sets. The syntax is -
set.intersection(set1, set2, set3 ... etc)
Here, set1 is required and other sets are optional. We can compare as many sets as we like, separated the sets with commas.
Examples of set intersection
In the given example, we have compared 2 sets, and returned a set with items that is present in all 2 sets -
set1 = {3, 2, 1}
set2 = {1, 2, 8}
result = set1.intersection(set2)
print(result)
Output of the above code -
{1, 2}
In the given example, we have compared 3 sets and returned a set with items that is present in all 3 sets -
set1 = {"m", "n", "p"}
set2 = {"n", "p", "o"}
set3 = {"p", "q", "n"}
result = set1.intersection(set2, set3)
print(result)
Output of the above code-
{'p', 'n'}
Examples of set intersection using & operator
We can also find the intersection of sets using the & operator. This works similar to the intersection() method. The following example demonstrates this -
set1 = {120, 341, 132, 190, 150}
set2 = {341, 132, 180, 150}
set3 = {120, 341, 132, 193, 180, 341}
print("set1 & set2 : ", set1 & set2)
print("set2 & set3 : ", set2 & set3)
Output of the above code:
set1 & set2 : {132, 341, 150}
set2 & set3 : {132, 180, 341}
Related Articles
Convert list to dictionary Python
Convert array to list Python
numpy dot product
glob in Python
Python heap implementation
zip function in Python
Remove last element from list Python
Check if list is empty Python
Remove element from list Python
Python split multiple delimiters
Python loop through list
Python iterate list with index
Python add list to list
Python random choice
Python dict inside list
Remove character from string Python
Python raise keyword