How to Check if Two Sets Have Common Elements in Python
To check if two sets have common elements in Python, use the
intersection() method or the isdisjoint() method. intersection() returns the common elements, and if it's not empty, the sets share elements. Alternatively, isdisjoint() returns False if there are common elements.Syntax
There are two main ways to check for common elements between two sets in Python:
set1.intersection(set2): Returns a new set with elements common to bothset1andset2.set1.isdisjoint(set2): ReturnsTrueifset1andset2have no elements in common, otherwiseFalse.
python
common_elements = set1.intersection(set2) # Check if common_elements is not empty if common_elements: print("Sets have common elements") # Or using isdisjoint if not set1.isdisjoint(set2): print("Sets have common elements")
Example
This example shows how to check if two sets share any elements using both intersection() and isdisjoint() methods.
python
set_a = {1, 2, 3, 4}
set_b = {3, 5, 7}
# Using intersection()
common = set_a.intersection(set_b)
if common:
print(f"Common elements found: {common}")
else:
print("No common elements")
# Using isdisjoint()
if not set_a.isdisjoint(set_b):
print("Sets have common elements")
else:
print("Sets do not have common elements")Output
Common elements found: {3}
Sets have common elements
Common Pitfalls
One common mistake is to check if intersection() returns True or False directly, but it actually returns a set. You must check if the returned set is empty or not.
Another pitfall is misunderstanding isdisjoint(): it returns True when sets have no common elements, so you need to negate it to check for common elements.
python
# Wrong way if set_a.intersection(set_b) == True: print("Common elements") # This will never run # Correct way if set_a.intersection(set_b): print("Common elements") # Wrong way if set_a.isdisjoint(set_b): print("Common elements") # This prints when no common elements # Correct way if not set_a.isdisjoint(set_b): print("Common elements")
Output
Common elements
Common elements
Quick Reference
| Method | Description | Returns | Check for common elements |
|---|---|---|---|
| intersection() | Returns set of common elements | Set (empty if none) | Check if result is not empty |
| isdisjoint() | Checks if sets have no common elements | Boolean | Use 'not' to check if common elements exist |
Key Takeaways
Use set1.intersection(set2) and check if the result is not empty to find common elements.
Use not set1.isdisjoint(set2) to check if two sets share any elements.
intersection() returns a set, not a boolean, so check its truthiness properly.
isdisjoint() returns True when sets have no common elements, so negate it to detect common elements.
Both methods are efficient and built-in ways to compare sets in Python.