CKTIS / Python
Set symmetric difference (`^`)
Use `^` to keep elements that belong to exactly one of two sets. The same operator performs bitwise XOR when both operands are integers.
Version: Python 3.12
Syntax
a ^ b
a.symmetric_difference(other)In Python 3.12, set ^ refers to the set operation written a ^ b. It creates a new set containing elements in a or b, but not in both, and leaves both operands unchanged. If you mix a set and a frozenset, the result has the type of the left operand.
For the built-in set types, ^ expects a set or frozenset on each side. If a is a set and b is a list, a ^ b raises TypeError. Use a.symmetric_difference(b) instead: the method accepts any iterable whose elements are hashable.
With two int operands, ^ performs bitwise XOR: a result bit is 1 where the corresponding input bits differ. Even when the sets contain integers, set ^ checks membership rather than comparing the bits of their elements.
Examples
a = {1, 2, 3}
b = {3, 4}
print(sorted(a ^ b))
print(6 ^ 3)
Result
[1, 2, 4] 5
The element `3` is in both sets, so it is left out. `sorted()` returns a list in a fixed order. The second line shows XOR on two integers.
Related lessons
- Python · Lesson 18 · Basic · Version: 3