Symmetric difference of two sets in Python | Example code

Use set.symmetric_difference() builtin function of Python to get the symmetric difference between two sets. You can also use the ^ operator for it.

set1.symmetric_difference(set2) 

Example find symmetric difference of two sets

Simple example code get set contains a mix of items that are not present in both sets.

set1 = {10, 20, 30}

set2 = {30, 40, 100}

new_set = set1.symmetric_difference(set2)

print(new_set)

Output:

Symmetric difference of two sets in Python

Another example using the ^ operator

set1 = {'A', 'B'}

set2 = {'A','C'}

new_set = set1 ^ set2

print(new_set)

Output: {‘B’, ‘C’}

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

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.