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 String startswith()
Python bytes()
Python Program to Calculate the Area of a Triangle
Python Program to Check If a String Is a Number (Float)
Python Program to Convert Celsius To Fahrenheit
Python Data Structures and Algorithms - Benjamin Baka
Python String center()
Python Program to Compute the Power of a Number
Python Program to Reverse a Number
Python getattr()
Python bytearray()
Python Global Keyword
Python String splitlines()
Python String islower()
Python String isalpha()
APIs in Node.js vs Python - A Comparison
Python Program to Catch Multiple Exceptions in One Line
Python Strings
Python Program to Count the Occurrence of an Item in a List
Python oct()
Java Program to Implement the Program Used in grep/egrep/fgrep
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python Program to Convert Decimal to Binary Using Recursion
Python Dictionary fromkeys()
Python Program to Get the Class Name of an Instance
Python Set intersection_update()
Python Operators
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python Program to Extract Extension From the File Name
Python String rfind()
Python Set isdisjoint()
Python String rindex()