difference
set.symmetric_difference
Returns a NEW set with elements in EITHER s or other but not both. Method form takes exactly one iterable; ^ requires a set.
s.symmetric_difference(other) | s ^ other Parameters
| Parameter | Purpose |
|---|---|
| other | A single iterable (method) or set (operator) |
| returns | A new set of elements unique to each side |
Examples
>>> {1, 2, 3} ^ {2, 3, 4}
{1, 4} Keeps elements found in exactly one side.
>>> {1, 2}.symmetric_difference([2, 3])
{1, 3} Method accepts an iterable.
>>> {1, 2} ^ {1, 2}
set() Identical sets yield the empty set.
>>> a = {1, 2}; b = {2, 3}
>>> a ^ b == b ^ a
True Symmetric difference IS commutative.
Gotcha
Unlike union/intersection/difference, the method form takes exactly ONE argument, not *others. It equals (a | b) - (a & b).
Related methods
set.difference
Returns a NEW set with elements from s that are NOT in any of the arguments. Method form takes iterables; - requires sets.
set.union
Returns a NEW set containing every element that appears in s or any of the arguments. The method accepts any iterable(s); the | operator requires all operands to be sets or frozensets.
set.difference_update
Removes from s in place every element found in any of the given iterables. Method form accepts iterables; -= requires sets.
← All Python set methods · List methods · list vs tuple vs set