Join Regular Classroom : Visit ClassroomTech

Python Set – symmetric_difference() Method

It is a method in python returns the symmetric difference of two sets i.e. returns a set where elements of both the sets are there but excluding their intersection. It doesn’t modifies the given set.

Syntax:
set1.symmetric_difference(set2)
or
set1^(set2)

Also Read: Python Set – difference_update() Method

Example 1:

# Python code to understand symmetric_difference() method in set
# www.codewindow.in

s1 = {1, 2, 3, 4, 5, 6, 7}
s = {1, 2, 3}

#symmetric difference of s and s1?
x = s1.symmetric_difference(s)
x1 = (s1|s)-(s1&s)
print(x)
print(x1)

Output:

{4, 5, 6, 7}
{4, 5, 6, 7}

Explanation:
Here it returned all the elements of both the sets but not the elements that were common (1, 2, 3) in both of them.

Example 2:

# Python code to understand symmetric_difference() method in set
# www.codewindow.in

s1 = {2, 5, 8, 7, 9}
s = {10, 5, 2}

#difference of s and s1
x = s^(s1)
print(x)

Output:

{7, 8, 9, 10}

Explanation:
Here it returned all the elements of both the sets but not the elements that were common (2, 5) in both of them.


Follow Us

You Missed

Also Checkout