The in-built intersection()
method in Python is used to return a new set that contains elements common in sets x
and y
.
Figure 1 below uses a Venn diagram to represent the new set created using this function.
x.intersection(y)
The intersection()
method requires at least one set to be passed as a parameter and compared. However, it is up to the user how many sets they would like to compare.
This method returns a new set that contains the intersection of the set that calls the method, and the set that is passed as a parameter.
#Finding the intersection of two setsx = {'Red', 'Blue', 'Purple', 'Orange'}y = {'Yellow', 'Orange', 'Blue', 'Turquoise'}z = x.intersection(y)print(z)
#Finding the intersection of more than two setsx = {'Cats', 'Dogs', 'Elephants', 'Seals'}y = {'Dogs', 'Lions', 'Seals', 'Parrots'}z = {'Snakes', 'Seals', 'Dogs', 'Rabbits'}common = x.intersection(y, z)print(common)