The intersection of two sets is the set of elements that are common to both sets.
For example if we have two sets A = {1, 2, 3}
and B = {2, 3, 4}
, the intersection is {2, 3}
, since this are the elements that are present in both sets.
The set
class defines the intersection()
method which returns a new set that is the intersection of the current set an another set(s) given as argument.
As you can see from the above example, the set.intersection method creates a new set with the common elements of both sets.
The set.intersection_update()
method
Unlike the intersection()
method, the intersection_update()
method does not create a new set. It instead modifies the existing set by removing all elements that are not present in both sets.
set1.intersection_update(set2, ...)
Note: Multiple iterables may be given as arguments.
The method, removes elements from set1
that are not common to both set1
and set2
.
passing multiple sets/iterables
The intersection_update()
, allows multiple iterables(not just sets) to be passed as arguments. Similarly, it modifies the current sets by removing the elements that are not common in all the iterables.
Using the &=
operator instead
The &=
is the operator version of the intersection_update()
method. However, with this approach, the argument must be set not just any iterable.
set1 &= set2
The operator removes the elements in set1 that are not common to both set1
and set2
.