English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we define two set variables and perform different set operations: union, intersection, difference, and symmetric difference.
To understand this example, you should understand the followingPython programmingTopic:
Python provides a data type named set, whose elements must be unique. It can be used to perform different set operations, such as union, intersection, difference, and symmetric difference.
# Program to perform different set operations, such as mathematical operations # Definition E = {0, 2, 4, 6, 8}; N = {1, 2, 3, 4, 5}; # Calculate the union of the set print("The union of E and N is", E | N) # Calculate the intersection of the set print("The intersection of E and N is", E & N) # Calculate the difference set of the set print("The difference set of E and N is", E - N) # Symmetric difference set print("The symmetric difference set of E and N is", E ^ N)
Output result
The union of E and N is {0, 1, 2, 3, 4, 5, 6, 8} The intersection of E and N is {2, 4} The difference set of E and N is {0, 8, 6} The symmetric difference set of E and N is {0, 1, 3, 5, 6, 8}
In this program, we use two different sets and perform different set operations on them. Similarly, it can also be completed by using the set method.