Python set operations (union, intersection, difference and symmetric difference)
This article demonstrates different operations on Python sets.
Examples:
Input :
A = {0, 2, 4, 6, 8}
B = {1, 2, 3, 4, 5}
Output :
Union : [0, 1, 2, 3, 4, 5, 6, 8]
Intersection : [2, 4]
Difference : [8, 0, 6]
Symmetric difference : [0, 1, 3, 5, 6, 8]
In Python, below quick operands can be used for different operations.
| for union.
& for intersection.
– for difference
^ for symmetric difference
# Program to perform different set operations# as we do in mathematics # sets are defineA = {0, 2, 4, 6, 8};B = {1, 2, 3, 4, 5}; # unionprint("Union :", A | B) # intersectionprint("Intersection :", A & B) # differenceprint("Difference :", A - B) # symmetric differenceprint("Symmetric difference :", A ^ B) |
Output:
('Union :', set([0, 1, 2, 3, 4, 5, 6, 8]))
('Intersection :', set([2, 4]))
('Difference :', set([8, 0, 6]))
('Symmetric difference :', set([0, 1, 3, 5, 6, 8]))
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


