Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python Set symmetric_difference() method



The Python Set symmetric_difference() method is used to obtain elements present in either of two sets but not in both.

Symmetric_difference is a set operation in mathematics and programming which is denoted by the symbol . When applied to sets A and B it returns a new set containing elements that are in A or B excluding those common to both. This operation disregards duplicate elements and order.

It is useful for comparing and manipulating data sets which is often employed in tasks like finding unique elements between collections or identifying differences in data. This operation facilitates efficient data analysis, set manipulation and algorithm design in various computational tasks.

Syntax

Following is the syntax and parameters of Python Set symmetric_difference() method −

set.symmetric_difference(other)

Parameter

This method accepts another set as a parameter, with which the symmetric difference is to be calculated.

Return value

This method returns a new set containing elements that are present in either the original set or the other set but not in both.

Example 1

Following is the example in which the symmetric_difference() method is used to find elements that are present in either set1 or set2 but not in both −

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
result = set1.symmetric_difference(set2)
print(result)  

Output

{1, 2, 5, 6}

Example 2

Here in this example symmetric_difference() method is chained to find elements present in exactly one of the three sets −

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
set3 = {4, 5, 6, 7}
result = set1.symmetric_difference(set2).symmetric_difference(set3)
print(result)   

Output

{1, 2, 4, 7}

Example 3

In this example we are checking the symmetrically difference with an empty set with the help of the symmetric_difference() method −

set1 = {1, 2, 3, 4}
empty_set = set()
result = set1.symmetric_difference(empty_set)
print(result)    

Output

{1, 2, 3, 4}
python_set_methods.htm
Advertisements