Python Set symmetric_difference() Method

Returns a new set with items from all the sets, except common items

Usage

The symmetric_difference() method returns a new set containing all items from both the sets, except common items.

If you want to modify the original set instead of returning a new one, use symmetric_difference_update() method.

The symmetric difference is actually the union of the two sets, minus their intersection.

Syntax

set.symmetric_difference(set)

Python set symmetric_difference() method parameters
ParameterConditionDescription
setRequiredA set to find difference in

Basic Example

# Compute the symmetric difference between two sets
A = {'red', 'green', 'blue'}
B = {'yellow', 'red', 'orange'}

print(A.symmetric_difference(B))
# Prints {'orange', 'blue', 'green', 'yellow'}
Set symmetric difference

Equivalent Operator ^

Set symmetric difference can be performed with the ^ operator as well.

A = {'red', 'green', 'blue'}
B = {'yellow', 'red', 'orange'}

# by method
print(A.symmetric_difference(B))
# Prints {'orange', 'blue', 'green', 'yellow'}

# by operator
print(A ^ B)
# Prints {'orange', 'blue', 'green', 'yellow'}

Symmetric Difference between Multiple Sets

The symmetric_difference() method doesn’t allow multiple sets.

However, using ^ operator, you can find symmetric difference between multiple sets.

A = {'red', 'green', 'blue'}
B = {'yellow', 'orange'}
C = {'blue', 'red', 'black'}

print(A ^ B ^ C)
# Prints {'orange', 'black', 'green', 'yellow'}