Python Program To Find Symmetric Difference Of Two Sets
Chapter:
Python
Last Updated:
27-09-2023 16:45:57 UTC
Program:
/* ............... START ............... */
# Define two sets
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
# Using symmetric_difference() method
symmetric_diff1 = set1.symmetric_difference(set2)
# Using ^ operator
symmetric_diff2 = set1 ^ set2
# Display the symmetric differences
print("Symmetric Difference using symmetric_difference():", symmetric_diff1)
print("Symmetric Difference using ^ operator:", symmetric_diff2)
/* ............... END ............... */
Output
Symmetric Difference using symmetric_difference(): {1, 2, 6, 7}
Symmetric Difference using ^ operator: {1, 2, 6, 7}
Notes:
-
We start by defining two sets, set1 and set2, using curly braces {}.
- set1 is initialized with elements {1, 2, 3, 4, 5}.
- set2 is initialized with elements {3, 4, 5, 6, 7}.
- We then use two different methods to find the symmetric difference of these sets.
- set1.symmetric_difference(set2) is used to find the symmetric difference using the symmetric_difference() method.
- set1 ^ set2 is used to find the symmetric difference using the ^ operator, which is a shorthand for the symmetric difference operation.
- We store the results of these two methods in the variables symmetric_diff1 and symmetric_diff2.
- Finally, we print out the symmetric differences using print() statements.