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.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 13 views 0 copies

Python code

26 lines
Python 3.9+
def 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

stdout
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

  1. Use the `^` operator directly: `set_a ^ set_b` for a concise symmetric difference.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.