What is the set symmetric_difference() method in Python?

Overview

The symmetric_difference() method in Python for two elements A and B is used to return the set of elements contained in both A and B but not common in both of them. In other words, it is used to produce the symmetric difference between two sets.

Syntax

A.symmetric_difference(B)

Parameter value(s)

Parameter

Description

A

This is the required argument. It is one of the sets we want to find its symmetric difference with a second set.

B

This is the required argument. It is one of the sets we want to find its symmetric difference with a second set.

Return value

The symmetric_difference() method returns a set of elements that represent the symmetrical difference between the two sets.

Code example

Let us create two sets, A and B, and then use the symmetric_difference() method to obtain the symmetric difference between both sets as follows:

A = {'a','b','c','d'}
B = {'a','f','g'}
symmetry = A.symmetric_difference(B)
print('The symmetry between A and B is=', symmetry)

Code explanation

  • Line 1: we defined set A

  • Line 2: we defined set B

  • Line 4: we used the symmetric_difference() method to obtain the symmetric difference between the two sets by assigning a variable named symmetry

  • Line 5: we printed the output

Note: we can use another way to find the symmetric difference between two sets by using the ^ operator.

The ^ operator in Python

As mentioned earlier, we can compute the symmetric difference between two sets by using the ^ operator. Therefore, let us find the symmetric difference between A and B sets using the ^ operator as follows:

A = {'a','b','c','d'}
B = {'a','f','g'}
# symmetric difference of two sets using ^ operator
print(A ^ B)

The code above shows that without having to go through that method of symmetric_difference(), one can easily use the ^ operator to compute the symmetric difference between two sets.

Free Resources