Set Difference and Symmetric Difference
Core idea
a - b (or a.difference(b)) keeps members of a that are absent from b. Reversing the operands can change the result. a ^ b (or a.symmetric_difference(b)) keeps members that occur in exactly one of the two sets. Neither operation modifies the original sets.
borrowed = {11, 12, 14}returned = {12, 15}print(sorted(borrowed - returned))15 is not borrowed, so it cannot appear in the result.
Compare both directions
a = {1, 2}b = {2, 3}print(sorted(a - b))print(sorted(b - a))Each difference starts from a different group.
Find changed registrations
old = {1, 3, 5}new = {3, 5, 7}print(sorted(old ^ new))1 was removed and 7 was added; shared members are excluded.
Common mistake
Symmetric difference is not union: shared members are removed, not included. It also differs from directional difference, which cannot return members exclusive to the right operand.
Practice
Compare yesterday and today’s shelf labels. Show labels missing today, new today, and all changed labels separately.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Difference and symmetric difference
Check your understanding of difference and symmetric difference.
What is printed?
print(sorted({1, 2} - {2, 3}))What is printed?
print(sorted({1, 2} ^ {2, 3}))What is printed?
print(sorted({2} ^ {2}))Which operation finds members added since yesterday?