set.symmetric_difference()
Returns a new set with the elements that are in exactly one of the two sets, never in both. Same as the ^ operator.
set.symmetric_difference(other)a.symmetric_difference(b) gives what the two sets do not share: everything in a or in b, minus what is in both. The operator form is a ^ b.
It is the quickest answer to "what is different between these two collections?", for example two versions of a guest list, and unlike set.difference() the order of the two sets does not matter.
Unlike set.union() and set.intersection(), this method takes exactly one other collection, not several.
Parameters
| Parameter | What it is |
|---|---|
otherrequired | A set or other iterable to compare with. |
Return value
A new set.
Examples
1In one or the other, not both
a = {1, 2, 3}
b = {3, 4}
print(a.symmetric_difference(b))
print(a ^ b)
print(b ^ a){1, 2, 4}
{1, 2, 4}
{1, 2, 4}2Compare two guest lists
old_list = {"Ana", "Ben", "Chloe"}
new_list = {"Ben", "Chloe", "Dan"}
changed = old_list ^ new_list
print("Changed:", sorted(changed))
print("Added:", sorted(new_list - old_list))
print("Dropped:", sorted(old_list - new_list))Changed: ['Ana', 'Dan'] Added: ['Dan'] Dropped: ['Ana']
3Same as union minus intersection
a = {1, 2, 3}
b = {2, 3, 4}
print((a | b) - (a & b) == a ^ b)True
Common mistakes
Passing more than one set
a.symmetric_difference(b, c) raises TypeError. Chain the operator instead: a ^ b ^ c (which keeps elements found in an odd number of the sets).
Questions people ask
How do I find the differences between two lists?
sorted(set(a) ^ set(b)) lists the values that appear in only one of them.
Is there an in-place version?
Yes: a ^= b or a.symmetric_difference_update(b).