The intersection of two sets is the set of all distinct elements that are common to both sets. It is represented using the symbol ∩
(pronounced "cap").
For example if we have sets A = {1, 2, 3}
and B = {2, 3, 4}
, the intersection of A
and B
is {2, 3}
since these are the elements that are present in both sets.
The set.intersection()
method in Python returns the intersection of two or more sets. It returns a new set containing the common distinct elements between the sets.
set1.intersection(set2, ...)
copy
set2 |
This can be a set or any other iterable objects. Multiple iterables may be given |
The method returns a new set that is the intersection of set1
and the other set(s) given as arguments.
With multiple arguments
In the following example, we pass multiple sets as arguments to the intersection()
method.
Using other iterables
In addition to sets, the arguments to the intersection method can be any other iterables such as lists, tuples, etc.
Using the &
operator instead
The ampersand symbol (&
) is the operator version of the intersection()
method. Similarly, it returns a new set with the common elements between the sets. With this approach, both arguments must be sets and not just any other iterable.
result = set1 & set2
copy