How does intersection() work in Python?

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.

Figure 1: The common elements in Set X and Y make Set Z. Set Z is an intersection of Set X and Y.

Syntax

x.intersection(y)

Parameters

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.

Return value

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.

Code

Example 1

#Finding the intersection of two sets
x = {'Red', 'Blue', 'Purple', 'Orange'}
y = {'Yellow', 'Orange', 'Blue', 'Turquoise'}
z = x.intersection(y)
print(z)

Example 2

#Finding the intersection of more than two sets
x = {'Cats', 'Dogs', 'Elephants', 'Seals'}
y = {'Dogs', 'Lions', 'Seals', 'Parrots'}
z = {'Snakes', 'Seals', 'Dogs', 'Rabbits'}
common = x.intersection(y, z)
print(common)

Free Resources