Python Collection intersection() Method

Example

Return a set that contains the items existing in both set x and set y:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y) 
print(z)

Run Instance

Definition and Usage

The intersection() method returns a set that contains the similarities between two or more sets.

Meaning: The returned set only contains items that exist in both sets, or if more than two sets are compared, then in all sets.

Syntax

set.intersection(set1, set2 ... etc)

Parameter Value

Parameter Description
set1 Required. The set in which the same items need to be searched.
set2

Optional. Other sets in which the same items need to be searched.

You can compare as many sets as you like.

Sets are separated by commas.

More Examples

Example

Compare 3 sets and return the items that exist in all 3 sets:

x = {"a", "b", "c"}
y = {"c", "d", "e"}
z = {"f", "g", "c"}
result = x.intersection(y, z)
print(result)

Run Instance