Skip to content

Module 8 · Python Data Structures — topic 15 of 22

Intersection

The intersection of sets contains only items that appear in all of them. Use & and intersection() to find common elements, shared interests and matching requirements.

Beginner 8 min read·Lesson 118 of 306 in Python Programming

Learning objectives

  • Find common items with & and intersection()
  • Intersect several collections
  • Use intersection for matching and filtering

Definition

The intersection of sets contains only items that appear in all of them. Use & and intersection() to find common elements, shared interests and matching requirements.

Introduction

The intersection of two sets contains only the items present in both. {1, 2, 3} & {2, 3, 4} is {2, 3}. It answers the question “what do these have in common?”

Why it matters

Finding students enrolled in every course, products available in all warehouses, or skills a candidate shares with a job description are all intersections.

Detailed explanation

a & b returns a new set of items in both a and b.

a.intersection(b, c) accepts several iterables and keeps only items present in all of them.

a &= b or a.intersection_update(b) keeps only common items in a.

If there are no common items, the result is an empty set, which is falsy: if a & b: tests whether anything is shared.

The size of an intersection is at most the size of the smaller set.

Intersection is commutative; for speed, Python works through the smaller set.

Syntax

Python
common = a & b
common = a.intersection(b, c)
if a & b:
pass
  • & returns a new set.
  • intersection() accepts several iterables.
  • An empty result is falsy.

Code examples

Common items

Python
asha = {"cricket", "chess", "music"}
ben = {"chess", "music", "coding"}
print(sorted(asha & ben))
print(sorted(asha.intersection(["music", "art"])))
Output
['chess', 'music']
['music']

Nothing shared

Python
a = {1, 2}
b = {3, 4}
print(a & b, bool(a & b))
Output
set() False

More examples

Matching candidates to a job

Python
required = {"python", "sql", "git"}
candidates = {
"Asha": {"python", "sql", "git", "docker"},
"Ben": {"python", "excel"},
"Chen": {"sql", "git", "python"},
}
for name, skills in candidates.items():
matched = required & skills
print(f"{name}: {len(matched)}/{len(required)} skills", "(qualified)" if matched == required else "")
warehouses = [{"pen", "pad", "ink"}, {"pen", "ink"}, {"ink", "pen", "clip"}]
print("In every warehouse:", sorted(set.intersection(*warehouses)))
Output
Asha: 3/3 skills (qualified)
Ben: 1/3 skills 
Chen: 3/3 skills (qualified)
In every warehouse: ['ink', 'pen']

Step-by-step explanation

  • required & skills keeps only the required skills each candidate has.
  • Comparing the result with required tells whether every requirement is met.
  • The conditional expression prints “(qualified)” or an empty string.
  • set.intersection(*warehouses) intersects every set in the list at once.

Expected output

Running “Matching candidates to a job” prints exactly:

TextOutput
Asha: 3/3 skills (qualified)
Ben: 1/3 skills
Chen: 3/3 skills (qualified)
In every warehouse: ['ink', 'pen']

Practical applications

  • Job portals match candidate skills against requirements.
  • Dating and social apps find shared interests.
  • Retail systems find products stocked in every store.

Best practices

  • Use if a & b: to test for any overlap, or isdisjoint() for the opposite.
  • Use set.intersection(*list_of_sets) for many sets.
  • Compare the intersection with the requirement set to test full coverage.

Common mistakes

Using and instead of &

Avoid

common = a and b

Prefer

common = a & b

and returns one of the sets based on truthiness; & computes the intersection.

Intersecting with a list via &

Avoid

{1, 2} & [2]

Prefer

{1, 2}.intersection([2])

The & operator needs two sets.

Key takeaways

  • Intersection keeps items present in all sets.
  • & and intersection() return new sets; &= updates in place.
  • An empty intersection is falsy.

Try it yourself

  1. 1
    Find the letters common to the words "programming" and "engineering".
  2. 2
    Find the days on which all three friends are free, given three sets of free days.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

13 questions cover the “Python Data Structures” module. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this module