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, ...)
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.
set1 = {1, 2, 3, 4, 5, 6}
set2 = {3, 4, 5, 6, 7, 8}
#get the intersection
result = set1.intersection(set2)
print(result)
With multiple arguments
In the following example, we pass multiple sets as arguments to the intersection()
method.
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {2, 3, 4, 5}
result = set1.intersection(set2, set3)
print(result)
Using other iterables
In addition to sets, the arguments to the intersection method can be any other iterables such as lists, tuples, etc.
set1 = {1, 2, 3}
set2 = [2, 3, 4] #list
set3 = (3, 4, 5) #tuple
result = set1.intersection(set2, set3)
print(result)
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
Get intersection using &
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
#get the intersection
result = set1 & set2
print(result)