Set symmetric_difference() Method in Python

Python Set symmetric_difference() Method

The symmetric_difference() method is used to get a new set that contains elements that are present in either of the two sets, but not in both. In other words, it returns the set of elements that are unique to each set and not common to both.

Syntax of the symmetric_difference() method:

result_set = set1.symmetric_difference(set2)

Parameters:

  • set1: The first set to perform the symmetric difference operation.
  • set2: The second set to perform the symmetric difference operation.

Example:

# Creating two sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Getting the symmetric difference between set1 and set2
result_set = set1.symmetric_difference(set2)

print(result_set)  # Output: {1, 2, 3, 6, 7, 8} (unique elements from both sets, but not common to both)

In this example, the symmetric_difference() method is applied to set1 and set2, and it returns a new set containing the elements that are present in either set1 or set2, but not in both (1, 2, 3, 6, 7, 8).

You can also use the ^ operator to perform the symmetric difference operation:

# Creating two sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Getting the symmetric difference using the ^ operator
result_set = set1 ^ set2

print(result_set)  # Output: {1, 2, 3, 6, 7, 8} (same result as using symmetric_difference())

Both methods, symmetric_difference() and ^ operator, will give you the same result for the symmetric difference operation. Choose the one that suits your coding style and preference.