intersection(*others) builds a new set with only the items that appear in the set and in every iterable you pass. The original set is not changed.
If nothing is shared the result is an empty set, which Python prints as set(). With no arguments, you simply get a copy of the set.
set.intersection() is an instance method of the built-in set type: call it on a set with dot notation, such as skills.intersection(...). No import is needed.
Syntax
Pass one or more iterables, and keep the returned set in a variable.
python
common = s.intersection(iterable)
common = s.intersection(iterable1, iterable2)
common = s & other_set
Call
What it does
{1, 2, 3}.intersection({2, 3, 4})
Returns {2, 3}, a new set of the items found in both.
{1, 2, 3}.intersection([3, 4], {3, 5})
Returns {3}: only 3 is in the set and in every iterable.
{1, 2}.intersection({3})
Returns set(): nothing is shared, so the result is an empty set.
a & b is a shortcut for a.intersection(b), but only between two sets. To shrink the existing set instead of making a new one, use intersection_update().
Method signatures
python
set.intersection(*others)
# returns: a new set with the items present in the set and in every iterable
# raises: TypeError if an argument is not iterable or an item is unhashable
Parameters
Parameter
Description
*others
Zero or more iterables: set, list, tuple, string, range, and so on. An item is kept only if it appears in all of them.
Return Value
Return Value
Description
set
A new set with the shared items. It is empty (set()) when nothing is shared.
Python Examples
Example 1 — Find the Skills Two Candidates Share
Intersect two skill sets and compare with the & operator.