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 setattr()
Python classmethod()
Python Program to Sort Words in Alphabetic Order
Python Program to Iterate Through Two Lists in Parallel
Python Program to Make a Flattened List from Nested List
Python Objects and Classes
Python Set union()
APIs in Node.js vs Python - A Comparison
Python String strip()
Python String format_map()
Python Set difference()
Python slice()
Python Program to Merge Mails
Python timestamp to datetime and vice-versa
Python String isnumeric()
Python all()
Python Program to Get the Full Path of the Current Working Directory
Python File I/O Operation
Python hex()
Python Program to Get File Creation and Modification Date
Python Program to Merge Two Dictionaries
Python Set pop()
Python Program to Find Numbers Divisible by Another Number
Python List pop()
Python abs()
Python Custom Exceptions
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python String splitlines()
Introduction to Scientific Programming with Python - Joakim Sundnes
Python eval()
Python Program to Access Index of a List Using for Loop
Python String isidentifier()