set.intersection()
Python · Sets
Theory
.intersection(other) returns a new set with only the items that appear in both sets. With a = {1, 2, 3} and b = {2, 3, 4}, a.intersection(b) is {2, 3}. If the sets share nothing, the result is an empty set, written set(). The operator form is a & b, and you can intersect several sets at once with a.intersection(b, c).
Python implements it efficiently by looping over the smaller set and checking each item for membership in the larger one, so it costs roughly O(min(len(a), len(b))). As with union, the method accepts any iterable while & needs sets on both sides. intersection_update() or &= keeps only the common items in the original set. A related check, a.isdisjoint(b), returns True when there is no overlap at all, without building a result set.
Why we use it
Finding overlap is a frequent analysis question: customers who bought in both months, skills shared by two candidates, products stocked in every store. intersection() answers it in one fast call.
When to use it
Use intersection() or & to find common values between groups. Use isdisjoint() if you only need to know whether any overlap exists. For overlapping rows of tabular data with several columns, use a pandas merge with an inner join instead.
How it works
- Call a.intersection(b)
- Pick the smaller set to loop over
- Take its next item
- Is the item also in the other set? Yes: Add it to the result. No: Skip it.
- Return {2, 3}; a and b are unchanged
Syntax
set1.intersection(set2)Example
a = {1,2,3}
b = {2,3,4}
print(a.intersection(b))Key points
- Equivalent to the & operator: a & b
- Returns an empty set if there's no overlap
- Loops over the smaller set, so it is fast
- isdisjoint() checks for no overlap without building a set
- intersection_update() or &= keeps only common items in place