Python Set symmetric difference Method | Example code

Use symmetric_difference() method to get symmetric difference set in Python. This method returns a new set that contains all items from both sets, but not the items that are present in both sets

set.symmetric_difference(set) 

Python Example get Set symmetric difference

Simple example code gets the elements that are not common in both sets.

set1 = {1, 2, 3, 4, 5}

set2 = {1, 2, 3, 6, 0}

new_set = set1.symmetric_difference(set2)

print(new_set)

Output:

Python Set symmetric difference Method

Another example

Find the symmetric difference using the ^ operator.

set1 = {'A', 'B'}

set2 = {'A','C'}

new_set = set1 ^ set2

print(new_set)

Output: {‘C’, ‘B’}

The symmetric_difference() method vs symmetric difference operator (^)

The symmetric_difference() method accepts one or more iterables that can be strings, lists, or dictionaries. And the symmetric difference operator (^) only applies to sets. If you use it with the iterables which aren’t sets, you’ll get an error.

set1 = {'A', 'B'}

set2 = ['A','C']

new_set = set1 ^ set2

print(new_set)

Output: TypeError: unsupported operand type(s) for ^: ‘set’ and ‘list’

Do comment if you have any doubts and suggestions on this Python set tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.