Python - Set symmetric_difference() Method


Advertisements

The Python set symmetric_difference() method is used to return a set which contains all elements which are either in first set or second set but not in both. This method takes only argument and can take a set or an iterable as an argument. Please note that, this method does not change the original set.

The below figure depicts two sets called A = {10, 20, 30, 40, 50, 60} and B = {40, 50, 60, 70}. As 40, 50 and 60 are common elements between A and B, hence intersection of these sets will be {40, 50, 60}. Similarly, union of these two sets will be {10, 20, 30, 40, 50, 60, 70}. The symmetric_difference() method can be expressed as:

  • A.symmetric_difference(B) is same as (AUB) - (AꓵB) = {10, 20, 30, 70}
  • B.symmetric_difference(A) is same as (BUA) - (BꓵA) = {10, 20, 30, 70}
Intersection of Sets

Syntax


set.symmetric_difference(iterable)

Parameters

iterable Required. specify set or iterable to compute symmetric_difference set.

Example: Symmetric difference set using set as an argument

In the below example, two sets called SetA and SetB are taken to compute Symmetric difference set using symmetric_difference() method.

SetA = {10, 20, 30, 40, 50, 60}
SetB = {40, 50, 60, 70}

print(SetA.symmetric_difference(SetB))

Output

{10, 20, 30, 70}

Example: Symmetric difference set using iterable as an argument

In the below example, a set called SetA and list called ListB are taken to compute Symmetric difference set using symmetric_difference() method.

SetA = {10, 20, 30, 40, 50, 60}
ListB = [40, 50, 50, 60, 60, 70]

print(SetA.symmetric_difference(ListB))

Output

{10, 20, 30, 70}

Sets Methods




Advertisements