0
0
Pythonprogramming~5 mins

Difference and symmetric difference in Python

Choose your learning style9 modes available
Introduction

Difference and symmetric difference help you find what is unique between two groups of items.

You want to find items in one list that are not in another.
You want to see what items are different between two sets.
You want to compare two collections and find unique elements.
You want to remove common items and keep only distinct ones.
Syntax
Python
set1.difference(set2)
set1 - set2

set1.symmetric_difference(set2)
set1 ^ set2

Difference shows items in set1 but not in set2.

Symmetric difference shows items in either set1 or set2 but not both.

Examples
Shows items in a but not in b.
Python
a = {1, 2, 3}
b = {2, 3, 4}
print(a.difference(b))
Another way to get difference using - operator.
Python
a = {1, 2, 3}
b = {2, 3, 4}
print(a - b)
Shows items in a or b but not both.
Python
a = {1, 2, 3}
b = {2, 3, 4}
print(a.symmetric_difference(b))
Another way to get symmetric difference using ^ operator.
Python
a = {1, 2, 3}
b = {2, 3, 4}
print(a ^ b)
Sample Program

This program shows how to find difference and symmetric difference between two sets.

Python
set1 = {10, 20, 30, 40}
set2 = {30, 40, 50, 60}

# Difference: items in set1 not in set2
diff = set1 - set2
print("Difference (set1 - set2):", diff)

# Symmetric difference: items in set1 or set2 but not both
sym_diff = set1 ^ set2
print("Symmetric difference:", sym_diff)
OutputSuccess
Important Notes

Difference is not symmetric: a - b is not the same as b - a.

Symmetric difference combines unique items from both sets.

Summary

Difference finds items only in the first set.

Symmetric difference finds items in either set but not both.

Use - for difference and ^ for symmetric difference.