In this example, we have defined two set variables and we have performed different set operations: union, intersection, difference and symmetric difference.
To understand this example, you should have the knowledge of the following Python programming topics:
Python offers a datatype called set whose elements must be unique. It can be used to perform different set operations like union, intersection, difference and symmetric difference.
Source Code
# Program to perform different set operations like in mathematics
# define three sets
E = {0, 2, 4, 6, 8};
N = {1, 2, 3, 4, 5};
# set union
print("Union of E and N is",E | N)
# set intersection
print("Intersection of E and N is",E & N)
# set difference
print("Difference of E and N is",E - N)
# set symmetric difference
print("Symmetric difference of E and N is",E ^ N)
Output
Union of E and N is {0, 1, 2, 3, 4, 5, 6, 8}
Intersection of E and N is {2, 4}
Difference of E and N is {8, 0, 6}
Symmetric difference of E and N is {0, 1, 3, 5, 6, 8}
In this program, we take two different sets and perform different set operations on them. This can equivalently done by using set methods.
Related posts:
Python slice()
Python Program to Find Sum of Natural Numbers Using Recursion
Operations on polynomials and series
Python Dictionary
Python Input, Output and Import
Python Program to Capitalize the First Character of a String
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python Program to Find HCF or GCD
Python Program to Convert Two Lists Into a Dictionary
Python Deep Learning Cookbook - Indra den Bakker
Python String isprintable()
How to get current date and time in Python?
Python List append()
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python Dictionary fromkeys()
Python eval()
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python tuple()
Python break and continue
Python all()
Python bin()
Python hex()
Python Dictionary update()
Python map()
Python Set add()
Python next()
Python String rpartition()
Python Program to Find LCM
Python Closures
Python Program to Find the Factors of a Number
Python Set symmetric_difference_update()
Python Program to Count the Number of Occurrence of a Character in String