Python Set intersection() Method
Description
The intersection() method is used to return elements contained in two or more sets, i.e., the intersection.
Syntax
intersection() method syntax:
set.intersection(set1, set2 ... etc)
Parameters
- set1 -- Required, the set to look for common elements
- set2 -- Optional, other sets to look for common elements, multiple allowed, separated by commas
Return Value
Returns a new set.
Example
Return a new set whose elements are contained in both set x and set y:
Example 1
x = {"apple", "banana", "cherry"}
y = {"google", "example", "apple"}
z = x.intersection(y)
print(z)
The output result is:
{'apple'}
Calculate the intersection of multiple sets:
Example 1
x = {"a", "b", "c"}
y = {"c", "d", "e"}
z = {"f", "g", "c"}
result = x.intersection(y, z)
print(result)
The output result is:
{'c'}
Python Sets