Hello friends! Many times we need to find what two groups have in common. In Python, the easiest way to do this is with sets. The intersection() method returns a new set containing only the items that are present in all the sets you compare. It answers questions like “which students are in both the Maths club and the Science club?” The original sets are not changed. Let’s understand it with examples.
set1.intersection(set2, set3, ...)
set1 & set2 & set3 # operator form
Basic Example
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a.intersection(b))
print(a & b)
print(a)
Output:
{3, 4}
{3, 4}
{1, 2, 3, 4}
You can compare more than two sets at once as well.
Intersection of More Than Two Sets
c = {4, 6, 8}
print(a.intersection(b, c))
print(a & b & c)
Output:
{4}
{4}
Only 4 is present in all three sets.
With Lists, Tuples and Ranges
Like union(), the method accepts any iterable, while the & operator needs sets on both sides:
print(a.intersection([2, 4, 9], range(4)))
Output:
{2}
range(4) is 0, 1, 2, 3, so only 2 is common to a, the list and the range.
But what happens if the sets have nothing in common? Let’s check.
When Nothing Is Common
print({1, 2}.intersection({3, 4}))
print({1, 2}.isdisjoint({3, 4}))
Output:
set()
True
An empty set prints as set() (not {}, which is an empty dictionary). If you only want to know whether two sets share anything, isdisjoint() is faster and clearer.
Changing a Set in Place: intersection_update() and &=
s = {1, 2, 3, 4}
s.intersection_update({2, 4, 6})
print(s)
s &= {4}
print(s)
Output:
{2, 4}
{4}
Read more: Python set intersection_update()
Now let’s use intersection() in a few practical situations.
Practical Examples
1. Students in Both Clubs
maths = {"Riya", "Aman", "Kabir", "Neha"}
science = {"Aman", "Neha", "Zoya"}
print(sorted(maths & science))
Output:
['Aman', 'Neha']
2. Common Letters in Two Words
print(sorted(set("python") & set("typhoon")))
Output:
['h', 'n', 'o', 'p', 't', 'y']
3. Common Items of Two Lists, Keeping Order and Duplicates
Sets lose order and duplicates. If you need to keep them, use a set only for the fast lookup:
l1 = [5, 3, 8, 1, 3]
l2 = [3, 1, 9]
lookup = set(l2)
common = [x for x in l1 if x in lookup]
print(common)
Output:
[3, 1, 3]
Practice Question
Here is a small question for you. Try it before you read the answer:
What does print({1, 2, 3} & {2, 3, 4} & {3, 4, 5}) print?
Answer: {3}. Only 3 is in all three sets.
So friends, to sum up: intersection() does not modify the original set, it returns a new one, and you use intersection_update() or &= when you want to change the original. When there are no common items, you get an empty set, shown as set(). And remember the difference: intersection keeps only the items common to all sets, while union keeps every item from every set. Practise with your own examples and it will become second nature.
More set methods: Set methods in Python · union() · difference() · issubset()