Set intersection is denoted by ∩ symbol. Python Set intersection() method returns a new set with elements that are common to all the sets.
Python Set intersection() method Syntax
X.intersection(Y) is equivalent to X ∩ Y.
X ∩ Y = Y ∩ X = The Set with the elements that are common to Set X and Y.
Parameter: This method accepts a Set as a parameter.
Return value: This method returns a new set with the elements that are common to all the sets.
Python Set intersection() method Example
In the following example, we have three sets X, Y and Z. We are demonstrating the use of intersection() method with the help of few examples. In the third print statement we are finding the intersection between all the three sets.
# Set X X = {1, 2, 3, 4, 5} # Set Y Y = {4, 5, 6, 7} # Set Z Z = {5, 6, 7, 8, 9} # X ∩ Y print(X.intersection(Y)) # Y ∩ Z print(Y.intersection(Z)) # X ∩ Y ∩ Z print(X.intersection(Y, Z))
Output:
Python Set Intersection Using & operator
We can also use & operator to find the intersection between sets. This works similar to the intersection() method. Lets take an example to understand the use of & operator. We are taking the same example that we have seen above but here we will use the & operator instead of intersection() method.
# Set X X = {1, 2, 3, 4, 5} # Set Y Y = {4, 5, 6, 7} # Set Z Z = {5, 6, 7, 8, 9} # X ∩ Y print(X&Y) # Y ∩ Z print(Y&Z) # X ∩ Y ∩ Z print(X&Y&Z)
Output:
{4, 5} {5, 6, 7} {5}
As you can see we got the same output that we have got using the intersection() method.
Leave a Reply