Set method

set.intersection()

Returns a new set with only the elements that appear in this set and in every other one given. Same as the & operator.

BeginnerEvery example below runs in your browser. Change the code and press Run.

set.intersection(*others)

a.intersection(b) keeps what the two have in common: the elements that are in a and in b. The originals do not change.

It answers questions like "which customers bought both products?" or "which skills does this candidate have from the list we need?".

a & b is the operator form for two sets. The method also accepts lists and other iterables, and several of them at once. If nothing is shared, the result is an empty set, printed as set().

Parameters

ParameterWhat it is
*others
optional
Any number of sets or other iterables. An element must be in all of them to stay.

Return value

A new set with the shared elements.

Examples

1What two sets share

Pythoneditable
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a.intersection(b))
print(a & b)
Output
{3, 4}
{3, 4}

2Skills that match the job

Pythoneditable
needed = {"python", "sql", "git"}
candidate = ["excel", "python", "git"]
match = needed.intersection(candidate)
print(f"{len(match)} of {len(needed)} skills:", sorted(match))
Output
2 of 3 skills: ['git', 'python']

3Present at every meeting

Pythoneditable
m1 = {"Ana", "Ben", "Chloe"}
m2 = {"Ben", "Chloe", "Dan"}
m3 = {"Chloe", "Ben"}
print(sorted(m1.intersection(m2, m3)))
Output
['Ben', 'Chloe']

4Nothing in common

Pythoneditable
odd = {1, 3, 5}
even = {2, 4}
common = odd & even
print(common)
print(bool(common))
Output
set()
False

To just ask "do they share anything?", set.isdisjoint() is clearer.

Common mistakes

Using and instead of &

a and b is a true/false test, not a set operation: it simply returns b when a is not empty.

Pythoneditable
a = {1, 2}
b = {2, 3}
print(a and b)
print(a & b)
Output
{2, 3}
{2}

Questions people ask

How do I find common elements in two lists in Python?

set(a).intersection(b), then sorted(...) if you want a list in a fixed order.

Is there an in-place version?

Yes: a &= b or a.intersection_update(b) keep only the shared elements in a.

Spotted a mistake on this page? Tell us