FREE E LEARNING PLATFORM
HOMEEXCEPTIONSOOPSJVMINTRO
 

Set intersection() method with examples




Set intersection is denoted by n 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 n Y.

X n Y = Y n 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 n Y
print(X.intersection(Y))

# Y n Z
print(Y.intersection(Z))

# X n Y n Z
print(X.intersection(Y, Z))

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 n Y
print(X&Y)

# Y n Z
print(Y&Z)

# X n Y n 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 Comment