Skip to content

Symmetric difference of two sets in Python | Example code

  • by

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 the symmetric difference of two sets

A 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 or suggestions on this Python set code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Your email address will not be published. Required fields are marked *