Python Set intersection() Method
Description
The intersection() method returns elements contained in two or more sets, that is, the intersection.
Syntax
Syntax of the intersection() method:
set.intersection(set1, set2 ... etc)
Parameters
- set1 -- required, the set in which to find common elements
- set2 -- optional, other sets in which to find common elements; multiple sets are allowed, separated by commas
Return Value
Returns a new set.
Example
Returns a new set whose elements are in both set x and set y:
Example 1
x
= {
"
apple
"
,
"
banana
"
,
"
cherry
"
}
y
= {
"
"
,
"
runoob
"
,
"
apple
"
}
z
=
x
.
intersection
(
y
)
(
z
)
The output is:
{'apple'}
Compute the intersection of multiple sets:
Example 1
x
= {
"
a
"
,
"
b
"
,
"
c
"
}
y
= {
"
c
"
,
"
d
"
,
"
e
"
}
z
= {
"
f
"
,
"
g
"
,
"
c
"
}
result
=
x
.
intersection
(
y
,
z
)
(
result
)
The output is:
{'c'}
Python Sets