Python

Symmetric_difference method in set

Click for All Topics

Symmetric_difference method in set

  • This method returns a new set that contain elements that are not common in both the set or we can say unique or distinct elements of all set.
  • This method takes only one element as an argument.
  • We can pass any iterable or collection data type element as an argument.
  • When we call this method with one set(main set) and pass one set(other set) then it iterates over the elements of both the set and check wether the element is present in another set if element is present in another set then it ignores the element if element is not present in other set it adds element in the new set(result set).
  • We can also use ^ (XOR) operator in place of symmetric_difference method.
  • When you have to find symmetric difference between multiple sets you can use this operator but the operand must be the set.

Syntax –

set_name.symmetric_difference(iterable)

Parameter –

  • Iterable → any iterable or collection e.g. list, tuple, dictionary, set, string
  • Return value → returns a new set

Example –

				
					set1={1,2,3,4,5}
set2={4,5,6,7,8}
print("Original set first:",set1)
print("Original set second:",set2)
s=set1.symmetric_difference(set2)
print("Resultant set:",s)

# Output -
# Original set first: {1, 2, 3, 4, 5}
# Original set second: {4, 5, 6, 7, 8}
# Resultant set: {1, 2, 3, 6, 7, 8}
				
			
  • In the above example, first we create two sets set1 and set2 with the elements.
  • After creating sets, print both the set on the output screen.
  • After that , call the symmetric difference method with set1 and pass set2 as argument and store the resultant set in variable s.
  • Then print the resultant set on the output screen.

Symmetric difference with list –

Example –

				
					my_set={'hello', 'this', 'is', 'edSlash'}
my_list=["Anurag", "Dubey"]
print("Original set:",my_set)
print("List:",my_list)
s=my_set.symmetric_difference(my_list)
print("Resultant set:",s)

# Output -
# Original set: {'hello', 'this', 'edSlash', 'is'}
# List: ['Anurag', 'Dubey']
# Resultant set: {'edSlash', 'is', 'Dubey', 'Anurag', 'hello', 'this'}
				
			

Symmetric difference using ^ (XOR) operator –

Example –

				
					set1={'A','B','C','D'}
set2={'C','D','E','F','G'}
print("Original set 1:",set1)
print("Original set 2:",set2)
s=set1^set2
print("Resultant set:",s)

# Output -
# Original set 1: {'A', 'B', 'C', 'D'}
# Original set 2: {'F', 'G', 'D', 'E', 'C'}
# Resultant set: {'A', 'B', 'F', 'G', 'E'}
				
			

Symmetric difference of multiple sets –

Example –

				
					s1={11,12,13,14}
s2={15,13,16,17}
s3={18,19,20,14}
print("set 1:",s1)
print("set 2:",s2)
print("set 3:",s3)
s=s1^s2^s3
print("Resultant set:",s)

# Output -
# set 1: {11, 12, 13, 14}
# set 2: {16, 17, 13, 15}
# set 3: {18, 19, 20, 14}
# Resultant set: {11, 12, 15, 16, 17, 18, 19, 20}