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 define A = {0, 2, 4, 6, 8}; B = {1, 2, 3, 4, 5}; # union print("Union :", A | B) # intersection print("Intersection :", A & B) # difference print("Difference :", A - B) # symmetric difference print("Symmetric difference :", A ^ B) |
chevron_right
filter_none
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]))
Recommended Posts:
- Difference between C and Python
- Difference between Python and C#
- Python Set | difference()
- Difference between == and is operator in Python
- Difference between various Implementations of Python
- Python | Difference between two lists
- Python | Difference in keys of two dictionaries
- Python | Pandas Index.difference()
- Python | Difference Between List and Tuple
- Python | Triple list difference
- Python | Set Difference in list of dictionaries
- Difference Between Go and Python Programming Language
- Difference between Method and Function in Python
- Python | Pandas TimedeltaIndex.difference
- Python | Difference between iterable and iterator
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


