How to Find Symmetric Difference Between Two Python Sets
Compute elements unique to each set and build a flag dictionary showing membership across two Python sets.
Python code
26 linesdef symmetric_difference_with_flags(set_a, set_b):
"""Return elements in either set but not both, grouped by which set they came from."""
only_in_a = set_a - set_b
only_in_b = set_b - set_a
print(f"Only in A: {only_in_a}")
print(f"Only in B: {only_in_b}")
print(f"Symmetric difference: {only_in_a | only_in_b}")
# Flag-based representation
flags = {}
for item in only_in_a:
flags[item] = "A_only"
for item in only_in_b:
flags[item] = "B_only"
for item in set_a & set_b:
flags[item] = "both"
return flags
if __name__ == "__main__":
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
result = symmetric_difference_with_flags(set1, set2)
print(f"Flagged result: {result}")
Output
Only in A: {1, 2}
Only in B: {5, 6}
Symmetric difference: {1, 2, 5, 6}
Flagged result: {1: 'A_only', 2: 'A_only', 5: 'B_only', 6: 'B_only', 3: 'both', 4: 'both'}
How it works
Set subtraction with set_a - set_b yields elements present in A but not B, producing only_in_a. The symmetric difference itself can be computed directly with the ^ operator, but here we manually create a flag dictionary by iterating over both exclusive sets and marking shared items as both. This approach gives richer insight than a plain symmetric difference when you need to know which original set each element came from.
Common mistakes
- Using `set_a.symmetric_difference(set_b)` when you need to distinguish which set each item came from — you lose source information.
- Forgetting that `set_a - set_b` and `set_b - set_a` are different results even for the same two sets.
- Assuming elements in `both` sets appear in the symmetric difference — they don't, since symmetric difference excludes intersection.
Variations
- Use the `^` operator directly: `set_a ^ set_b` for a concise symmetric difference.
- Use a dictionary comprehension: `{item: 'A_only' for item in only_in_a} | {item: 'B_only' for item in only_in_b}`.
Real-world use cases
- Comparing two user permission lists to find who has access to only one system versus both.
- Detecting configuration drift between two servers by flagging which host has an extra setting.
- Diffing API response fields to see which endpoint returned data that the other missed.
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.