How to use function symmetric_difference in Python? - with practical example
Symmetric difference is a set operation in Python that returns a new set with elements that are present in either of the sets, but not in both. It is represented by the caret (^) operator or by using the symmetric_difference() method.
Example 1:
Let's say we have two sets, set1 and set2, and we want to find the symmetric difference between them.
Step 1: Define two sets
Step 2: Use the caret (^) operator to find the symmetric difference
Step 3: Print the result
In this example, we have two sets, set1 and set2. The symmetric difference between the two sets is {1, 2, 3, 6, 7, 8}, which are elements present in either set1 or set2, but not in both. Example 2: Let's use the symmetric_difference() method to find the symmetric difference between two sets. Step 1: Define two sets Step 2: Use the symmetric_difference() method to find the symmetric difference Step 3: Print the result
In this example, we have two sets, set3 and set4. The symmetric difference between the two sets is {10, 20, 30, 60, 70, 80}, which are elements present in either set3 or set4, but not in both.
set1 = {1, 2, 3, 4, 5} set2 = {4, 5, 6, 7, 8} sym_diff = set1 ^ set2 print(sym_diff)
In this example, we have two sets, set1 and set2. The symmetric difference between the two sets is {1, 2, 3, 6, 7, 8}, which are elements present in either set1 or set2, but not in both. Example 2: Let's use the symmetric_difference() method to find the symmetric difference between two sets. Step 1: Define two sets Step 2: Use the symmetric_difference() method to find the symmetric difference Step 3: Print the result
set3 = {10, 20, 30, 40, 50} set4 = {40, 50, 60, 70, 80} sym_diff = set3.symmetric_difference(set4) print(sym_diff)
In this example, we have two sets, set3 and set4. The symmetric difference between the two sets is {10, 20, 30, 60, 70, 80}, which are elements present in either set3 or set4, but not in both.
Comments
Post a Comment