Python Set Intersection():

The intersection() method returns a new set that contains elements common from both sets.

Method signature

The signature for the intersection() method is as shown below. Here, It performs the intersection of set A with sets given in the parameter, and the result is stored in set C.

C=A.intersection(B1,B2,..)

Method parameters and return type

  • The intersection() method takes zero or more sets as a parameter.
  • However, the intersection() function returns a new set, consisting of values common from all sets(B1,B2,…) with set A. It returns a copy of set A only if the parameter is absent.

Python Set Intersection Examples:

Example 1:

In this example, let us take a set A and set B with a set of numbers.

#Initializing the Set
A={18,13,48,36,65}
B={22,36,54,13,5}

# Performing intersection operation and storing result in new set C
C=A.intersection(B)
#Printing a result
print("A∩B is ",C)
# If no parameter is passed it returns set itself
D=A.intersection()
#Printing a result
print("No parameter passed in intersection",D)

Output

A∩B is  {36,13}
No parameter passed in intersection {48, 65, 18, 36, 13}

Example 2:

In this case, let us consider a set of students who opted for various optional subjects. If we want to find the list of students who had opted for computer and sport or computer and pt or all three subjects we can get it using the intersection method. Moreover, if the set doesn’t contain an element present in all three sets, it returns an empty set.

#Initializing the Set
computer={"Ram", "Jimmy", "Keya"}
sport={"Kim", "Sam","Keya", "Tom"}
pt={"John","Sam", "Ram"}
#Using intersection method
r1=computer.intersection(sport)
r2=computer.intersection(pt)
r3=computer.intersection(sport,pt)
#Printing a set
print("Students who opted for computer and sport ",r1)
print("Students who opted for computer and pt ",r2)
print("Students who opted for all three subjects ",r3)

Output

Students who opted for computer and sport  {'Keya'}
Students who opted for computer and pt  {'Ram'}
Students who opted for all three subjects  set()

Example 3:

In this example, let us demonstrate the intersection() method on a mixed set. At this time, we can see no data elements are common in set c1 with all the other sets. Hence, the intersection will return an empty set.

#Initializing the Set
c1={"Kim",25,8.5}
c2={"Sam",25,10}
c3={"Raj",22,1.5}
c4={"Roy",32,14}
# Using intersection method
c=c1.intersection(c2,c3,c4)
# Printing a Set
print ("Result of intersection ",c)

Output

Result of intersection  set()

Conclusion

The intersection() method selects the common elements with other sets in the parameter. However, it returns a set itself if no parameter passed.

References

Happy Learning 🙂