How to Find Intersection of Two Sets in Python
To find the intersection of two sets in Python, use the
intersection() method or the & operator. Both return a new set containing elements common to both sets.Syntax
You can find the intersection of two sets using either the intersection() method or the & operator.
set1.intersection(set2): Returns a new set with elements common to bothset1andset2.set1 & set2: Another way to get the intersection using the&operator.
python
set1.intersection(set2)
# or
set1 & set2Example
This example shows how to find the intersection of two sets using both the intersection() method and the & operator.
python
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# Using intersection() method
common_elements_method = set1.intersection(set2)
# Using & operator
common_elements_operator = set1 & set2
print("Intersection using method:", common_elements_method)
print("Intersection using operator:", common_elements_operator)Output
Intersection using method: {3, 4}
Intersection using operator: {3, 4}
Common Pitfalls
One common mistake is trying to use the intersection() method without parentheses, which will return a method object instead of the intersection set. Another is confusing intersection with union, which combines all elements instead of common ones.
python
set1 = {1, 2, 3}
set2 = {2, 3, 4}
# Wrong: missing parentheses
wrong = set1.intersection
print(wrong) # This prints a method object, not the intersection
# Right:
right = set1.intersection(set2)
print(right) # Correct intersection outputOutput
<built-in method intersection of set object at 0x7f...>
{2, 3}
Quick Reference
| Operation | Syntax | Description |
|---|---|---|
| Intersection (method) | set1.intersection(set2) | Returns a new set with elements common to both sets |
| Intersection (operator) | set1 & set2 | Returns a new set with elements common to both sets |
| Union | set1.union(set2) or set1 | set2 | Returns a new set with all elements from both sets |
| Difference | set1.difference(set2) or set1 - set2 | Returns elements in set1 not in set2 |
Key Takeaways
Use
intersection() method or & operator to find common elements between two sets.Always include parentheses when calling
intersection() to get the result set.Intersection returns only elements present in both sets, not all elements combined.
Sets are unordered collections, so the order of elements in the result is not guaranteed.
Use union and difference methods for other set operations.