Set method

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.

IntermediateEvery example below runs in your browser. Change the code and press Run.

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

ParameterWhat it is
other
required
A set or other iterable to compare with.

Return value

A new set.

Examples

1In one or the other, not both

Pythoneditable
a = {1, 2, 3}
b = {3, 4}
print(a.symmetric_difference(b))
print(a ^ b)
print(b ^ a)
Output
{1, 2, 4}
{1, 2, 4}
{1, 2, 4}

2Compare two guest lists

Pythoneditable
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))
Output
Changed: ['Ana', 'Dan']
Added: ['Dan']
Dropped: ['Ana']

3Same as union minus intersection

Pythoneditable
a = {1, 2, 3}
b = {2, 3, 4}
print((a | b) - (a & b) == a ^ b)
Output
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).

Spotted a mistake on this page? Tell us