Introduction

Python provides several in-built methods for working with sets, which are essentially unordered collections of unique elements. The symmetric difference operation on sets in Python is one such method, which returns a new set containing elements that are unique to each of the input sets. In other words, it returns the elements that are in either of the sets, but not in both. This tutorial will cover the basics of symmetric difference operation on sets in Python, including how to perform it using the built-in set() function, what the output looks like, and some practical examples of how it can be useful in data analysis and other applications.

Table of Contents :

  • Symmetric difference operation 
    • Symmetric difference operation using the symmetric_difference method
    • Symmetric difference operation using the symmetric difference operator

Symmetric difference operation :

  • Symmetric difference operation of two or more sets in Python returns a new set which contains the elements that are present in the sets but not in their intersection part. 
  • We can do symmetric difference on sets in Python using the : 
    • symmetric_difference() method
    • symmetric difference operator '-'

Symmetric difference operation using the symmetric_difference method : 

  • The built-in  symmetric_difference()   method can be used to get symmetric difference of two or more sets in Python.
  • The basic syntax of using the  symmetric_difference()   method is :  new_set = set_1.symmetric_difference(set_2, set_3, set_4,...) 
  • The  symmetric_difference()   method can also accept iterable objects as arguments.
  • The  symmetric_difference()   method converts the iterable object into set before applying the symmetric difference operation.
  • Code Sample : 

set_1 = {1, 2, 3, 4}
set_2 = {2, 4, 5, 6, 7}
new_set = set_1.symmetric_difference(set_2)

print(f"Value of set_1 = {set_1}")
print(f"Value of set_2 = {set_2}")
print(f"Value of new_set = {new_set}")

# Output
# Value of set_1 = {1, 2, 3, 4}
# Value of set_2 = {2, 4, 5, 6, 7}
# Value of new_set = {1, 3, 5, 6, 7}


Symmetric difference operation using the symmetric difference operator '^' :

  • The symmetric difference operator  can be used in python to find symmetric difference of two sets.
  • The basic syntax of using a symmetric difference operator is :  new_set = set_1 ^ set_2 
  • The symmetric difference operator allows only sets as operands.
  • We cannot find symmetric difference of iterable objects with symmetric difference operator.
  • Code Sample : 

set_1 = {1, 2, 3, 4}
set_2 = {2, 4, 5, 6, 7}
new_set = set_1 ^ set_2

print(f"Value of set_1 = {set_1}")
print(f"Value of set_2 = {set_2}")
print(f"Value of new_set = {new_set}")

# Output
# Value of set_1 = {1, 2, 3, 4}
# Value of set_2 = {2, 4, 5, 6, 7}
# Value of new_set = {1, 3, 5, 6, 7}


Prev. Tutorial : Difference operation on sets

Next Tutorial : Subsets