How does symmetric_difference() work in Python?

The symmetric_difference() method in Python is used to return a new set with the symmetric difference of two sets.

Symmetric difference refers to elements that exist in two sets but not in their intersections.

The blue shaded regions represent the symmetric difference of Set X and Set Y
The blue shaded regions represent the symmetric difference of Set X and Set Y

Syntax

set1.symmetric_difference(set2)

Parameters and return value

This method only requires one set to be passed as a parameter, which the method then compares with the set that calls the method.

A set that contains the symmetric difference is returned.

Code

x = {'Cats', 'Dogs', 'Elephants', 'Seals'}
y = {'Dogs', 'Lions', 'Seals', 'Parrots'}
z = x.symmetric_difference(y)
print(z)

Free Resources