Tutorial Study Image

Python symmetric_difference()

The symmetric_difference() function in python returns a new set that containing the symmetric difference of two sets. The symmetric difference means the set of elements are either in the first set or in the second set. It doesn't contain common elements in the set.


A.symmetric_difference(B) #where A & B are sets
 

symmetric_difference() Parameters:

The symmetric_difference() function takes sets as its parameter. Python has another option for finding the symmetric difference that is by using the ^ operator.

Parameter Description Required / Optional
A & B The set to check for matches in Required

symmetric_difference() Return Value

The return value is always a set containing a mix of elements except the common elements.

Input Return Value
sets a set with symmetric difference

Examples of symmetric_difference() method in Python

Example 1: How symmetric_difference() works in Python?


A = {1, 2, 3, 4}
B = {2, 5, 6 }
C = {7, 5}

print(A.symmetric_difference(B))
print(B.symmetric_difference(A))

print(A.symmetric_difference(C))
print(B.symmetric_difference(C))
 

Output:


{1, 3, 4, 5, 6}
{5, 6, 4, 1, 3}
{1, 3, 4, 5, 6, 7}
{'2', '5', '7'}

Example 2: Symmetric-difference using ^ operator


X = {1, 2, 3, 4}
Y = {5, 3, 1}

print(X ^ Y)
print(Y ^ X)

print(X ^ X)
print(Y ^ Y)
 

Output:


{2, 4, 5}
{4, 2, 5}
set()
set()