Skip to main content

symmetric_difference()

The symmetric_difference() function in Python is a method used with sets to return a new set that contains elements that are present in either of the sets, but not in both. It does not modify the original sets, and the resulting set is the symmetric difference of the two sets.

Parameter Values

Parameter Description
iterable

A set or another iterable (e.g., list, tuple, dictionary) whose symmetric difference is to be found with the original set.

Return Values

The symmetric_difference() method returns a new set.

How to Use symmetric_difference() in Python

Example 1:

The symmetric_difference() method returns a new set containing elements that are in either of the sets, but not common to both sets.

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
result = set1.symmetric_difference(set2)
print(result) # Output: {1, 2, 5, 6}
Example 2:

The method does not modify the original sets, it creates and returns a new set with the symmetric difference.

set_a = {10, 20, 30, 40}
set_b = {30, 40, 50, 60}
new_set = set_a.symmetric_difference(set_b)
print(new_set) # Output: {10, 20, 50, 60}
Example 3:

The symmetric difference of sets is the same as the exclusive OR (XOR) operation on the sets at the element level.

set_x = {7, 8, 9}
set_y = {5, 8, 9}
result_set = set_x.symmetric_difference(set_y)
print(result_set) # Output: {5, 7}