The set.intersection(*others) method returns a brand-new set containing only the elements common to the calling set and all specified iterables.
Non-Destructive Intersection: Mathematically denoted as A ∩ B, this operation leaves all input collections unmodified. When working strictly between set objects, you can also use the bitwise AND operator (&). To update the calling set in-place instead of creating a new one, use intersection_update(). For related operations, see union(), difference(), and isdisjoint().
In Python, computing the common elements can be performed via the method call or the binary ampersand (&) operator:
new_set = set_instance.intersection(*others)
new_set = set_a & set_b
| Syntax Form | Accepted Types | Behavioral Description |
|---|---|---|
*others |
Any iterable (set, list, tuple, dict, string, generator) | Zero or more collections evaluated for shared membership. |
set_a & set_b |
set or frozenset only |
Operator syntax. Both operands must be sets; passing non-set collections raises a TypeError. |
| Return Value | set |
A brand-new set containing elements present across all specified collections. |
When comparing two sets, only elements present in both sets appear in the result. Neither input set is modified:
A = {1, 2, 3}
B = {3, 4, 5}
# Compute intersection using & operator
res_op = A & B
print("A & B:", res_op)
# Compute intersection using intersection() method
res_meth = A.intersection(B)
print("A.intersection(B):", res_meth)
# Verify originals remain unchanged
print("Set A unchanged:", A)
print("Set B unchanged:", B)
Output:
A & B: {3}
A.intersection(B): {3}
Set A unchanged: {1, 2, 3}
Set B unchanged: {3, 4, 5}
Verifying the resulting data type and memory identity using type():
x = A & B
print("Type of x:", type(x))
print("New set instance:", id(x) != id(A))
Output:
Type of x: <class 'set'>
New set instance: True
& Operator vs. intersection() Method 🔝While both syntactic forms produce identical sets, their parameter flexibility differs significantly:
intersection() method: Accepts any Python iterable (such as lists, tuples, or strings).& operator: Strictly requires both operands to be set instances. Other types trigger an immediate TypeError.A = {"a", "b", "c"}
B_list = ["a", "x", "y"]
# 1. Method accepts list directly
print("intersection() with list:", A.intersection(B_list))
# 2. Operator requires set operand
try:
invalid_op = A & B_list
except TypeError as err:
print("Operator TypeError caught:", err)
Output:
intersection() with list: {'a'}
Operator TypeError caught: unsupported operand type(s) for &: 'set' and 'list'
You can find common elements across three or more collections simultaneously. Only elements present in all inputs are retained:
A = {"a", "b", "c"}
B = {"a", "y", "z"}
C = {"a", "k", "l"}
# Chaining operator: (A & B) & C
print("Chained operator (A & B & C):", A & B & C)
# Passing multiple mixed iterables to intersection()
common_multi = A.intersection(B, ["a", "k", "l"], ("a", "m"))
print("Multi-iterable intersection():", common_multi)
Output:
Chained operator (A & B & C): {'a'}
Multi-iterable intersection(): {'a'}
Passing a raw string unpacks it character by character. When matching individual characters, this works automatically; when matching full words, wrap target strings inside a collection:
# Character-level intersection
chars = {"a", "b", "c", "x", "y"}
common_chars = chars.intersection("Alex")
print("Common characters with 'Alex':", common_chars)
# Word-level intersection: bare string vs list of strings
team = {"Alex", "Maria", "David"}
print("Bare string (empty match): ", team.intersection("Alex"))
print("Wrapped in list (word match):", team.intersection(["Alex"]))
Output:
Common characters with 'Alex': {'x'}
Bare string (empty match): set()
Wrapped in list (word match): {'Alex'}
["Alex"]) or set (e.g. {"Alex"}).
intersection() vs. intersection_update() 🔝Choosing between intersection() and intersection_update() depends on whether you need immutability or in-place memory optimization:
| Feature | intersection() / A & B |
intersection_update() / A &= B |
|---|---|---|
| Mutation | Non-destructive (new set allocated) | In-place mutation (modifies caller directly) |
| Return Value | New set instance |
None |
| Time Complexity | O(min(len(A), len(B))) average | O(min(len(A), len(B))) average |
| Auxiliary Space | O(len(result)) memory allocation | O(1) space (no allocation) |
Find common tags or topics between two user profiles to generate mutual recommendations:
def find_mutual_interests(user1_tags: set[str], user2_tags: list[str]) -> set[str]:
return user1_tags.intersection(user2_tags)
profile_a = {"python", "machine-learning", "cloud", "docker"}
profile_b = ["python", "docker", "kubernetes", "go"]
print("Shared interests:", sorted(find_mutual_interests(profile_a, profile_b)))
Output:
Shared interests: ['docker', 'python']
Isolate accounts holding active privileges across multiple secure access tiers:
def find_dual_clearance_users(tier1: set[str], tier2: set[str]) -> set[str]:
return tier1 & tier2
finance_team = {"alice", "bob", "charlie"}
audit_team = {"bob", "charlie", "diana"}
print("Dual clearance accounts:", sorted(find_dual_clearance_users(finance_team, audit_team)))
Output:
Dual clearance accounts: ['bob', 'charlie']
intersection() returns an empty set (set()).set().A.intersection() returns a distinct shallow copy of A.base = {10, 20}
# 1. Zero arguments returns shallow copy
copy_set = base.intersection()
print("Zero arguments:", copy_set, "Distinct:", copy_set is not base)
# 2. Disjoint sets yield empty set
print("Disjoint intersection:", base.intersection({99, 100}))
# 3. Intersecting with empty set
print("Empty set intersection:", base.intersection(set()))
Output:
Zero arguments: {10, 20} Distinct: True
Disjoint intersection: set()
Empty set intersection: set()
Practice hands-on drills, multi-iterable comparisons, and real-world filtering exercises in our companion Jupyter Notebook:
Explore interactive code cells, benchmark execution speeds, test string character filtering nuances, and run self-validating assertions.
View on GitHub Run in Google ColabRun these unit checks directly in Python or your local environment to verify intersection operations:
def test_set_intersection():
s1 = {1, 2, 3, 4}
s2 = {3, 4, 5}
assert s1.intersection(s2) == {3, 4}
assert s1 & s2 == {3, 4}
assert s1 == {1, 2, 3, 4}
assert s1.intersection([3, 4], (4, 5)) == {4}
assert s1.intersection({99}) == set()
print("All set.intersection() assertion tests passed! 100% verified.")
test_set_intersection()
Output:
All set.intersection() assertion tests passed! 100% verified.
Mutates the calling set in-place to retain only elements found in all specified collections.
Combines all unique elements gathered across multiple collections into a new set.
Computes elements unique to the calling set, excluding items found in other iterables.
Determines whether two sets share zero common elements, returning True or False.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.