Python Set symmetric_difference_update() Method

The symmetric_difference_update() method modifies a set by keeping only the elements that are in either of the two sets, but not in both.

Syntax

set1.symmetric_difference_update(set2)

Parameters

set2: Another set (or any iterable) to find the symmetric difference with.

Return Value

Returns None. It modifes the original set in place.

Examples

Example 1: Symmetric difference update of two sets

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

set1.symmetric_difference_update(set2)
print(set1) # Output: {1, 2, 3, 6, 7, 8}

Example 2: Symmetric difference update with different iterable types

The symmetric_difference_update() method also accepts iterables of different types, such as lists or tuples, as arguments.

set1 = {1, 2, 3, 4, 5}
list1 = [4, 5, 6, 7, 8] # a list

set1.symmetric_difference_update(list1)
print(set1) # Output: {1, 2, 3, 6, 7, 8}

Using The ^= Operator

The ^= is the shorthand for performing a set difference update.

For example:

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8} 

set1 ^= set2
print(set1) # Output: {1, 2, 3, 6, 7, 8}

The ^= operator only works with sets and doesn’t support other iterables like lists or tuples.