How to Find Difference of Two Sets in Python Easily
In Python, you can find the difference of two sets using the
- operator or the .difference() method. This returns a new set with elements in the first set that are not in the second set.Syntax
You can find the difference between two sets using either the - operator or the .difference() method.
set1 - set2: Returns a set with elements inset1but not inset2.set1.difference(set2): Does the same as above but as a method call.
python
difference_set = set1 - set2
# or
difference_set = set1.difference(set2)Example
This example shows how to find the difference between two sets of numbers. It prints the elements that are only in the first set.
python
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 6}
diff = set1 - set2
print(diff) # Output: {1, 2, 5}
# Using the difference() method
diff_method = set1.difference(set2)
print(diff_method) # Output: {1, 2, 5}Output
{1, 2, 5}
{1, 2, 5}
Common Pitfalls
One common mistake is to expect the difference to be symmetric. The difference set1 - set2 only removes elements found in set2 from set1. It does not remove elements unique to set2 from set1.
To get elements unique to both sets, use the symmetric difference.
python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Wrong: expecting symmetric difference
diff_wrong = set1 - set2
print(diff_wrong) # Output: {1, 2} (only from set1)
# Right: symmetric difference
sym_diff = set1.symmetric_difference(set2)
print(sym_diff) # Output: {1, 2, 4, 5}Output
{1, 2}
{1, 2, 4, 5}
Quick Reference
| Operation | Description | Example |
|---|---|---|
| Difference (-) | Elements in set1 not in set2 | {1,2,3} - {2,3} = {1} |
| Difference method | Same as - operator | {1,2,3}.difference({2,3}) = {1} |
| Symmetric difference | Elements in either set, but not both | {1,2,3}.symmetric_difference({2,3,4}) = {1,4} |
Key Takeaways
Use the - operator or .difference() method to find elements in one set not in another.
The difference is not symmetric; it only removes elements of the second set from the first.
For elements unique to both sets, use symmetric_difference().
Set difference returns a new set and does not change the original sets.
Sets are unordered collections, so the output order may vary.