Python Set symmetric_difference() Method Tutorial

In this section, we will learn what the Set symmetric_difference() method is and how to use it in Python.

What is Set symmetric_difference() Method in Python?

The Python Set symmetric_difference() method takes a reference to a set object and compares its elements with the Set object that invoked this method (AKA the original Set). After that, it will return a new Set object that contains those elements of both Sets that are not common on the other.

For example, if the original Set had a value like 3 but the reference Set object didn’t have this value (or vice versa), then the value 3 will be part of the elements of the returned Set object.

There’s another method called symmetric_difference_update() that does the same task. The difference however is that the symmetric_difference() method returns a new Set object, while the symmetric_difference_update() method updates the original Set object by removing those elements of the original Set that are also in the reference Set and at the same time add those elements of the Reference Set that are not common in the original Set, to this original Set object.

Python Set symmetric_difference() Method Syntax:

set.symmetric_difference(SetReference)

Set symmetric_difference() Method Parameter:

The method takes one argument and that is a reference to a Set object.

Set symmetric_difference() method Return Value

The return value of this method is a new Set object that contains only those elements that are in either the original or reference Set object but not both.

Example: using python set symmetric_difference() method

set1 = {1,2,3,4,5,6,7,8,9,10}

set2 = {1,2,3,4,5,500,600,700}

result = set1.symmetric_difference(set2)

print(result)

Output:

{6, 7, 8, 9, 10, 500, 600, 700}
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies