Python Reference ยท Dictionaries and Sets
Python set.intersection() method
Reference for Python set.intersection(): elements common to a set and one or more iterables, the & operator, no-argument behavior and typical uses.
The intersection() method returns a new set holding the elements that appear in the set and in every one of the given iterables. The original sets are not changed.
It answers "what do these have in common?": shared tags, users present in two lists, keys two records both define. The & operator does the same for sets, while the method also accepts other iterables.
{1, 2, 3}.intersection({2, 3, 4}) # {2, 3}
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
set.intersection(*others) set & other
| Name | Description |
|---|---|
*others |
Zero or more iterables. The result keeps only elements present in all of them. |
other |
For &, the right side must be a set or frozenset. |
Return value: a new set. With no arguments, a copy of the original.
Raises: TypeError if an argument is not iterable or holds unhashable elements.
Usage notes
- It does not mutate. Use
set.intersection_update()or&=to update in place. - Empty overlap gives
set(), never an error. - Order of operands does not matter for the content of the result, though CPython iterates the smaller set for speed.
- The method accepts any iterable;
&raisesTypeErrorfor a list. - Dictionary views support
&directly:d1.keys() & d2.keys()returns a set of shared keys. - Disjoint test. To only ask whether two sets overlap,
set.isdisjoint()avoids building a result. - Result type follows the left operand: a
frozenseton the left gives afrozenset.