A Python set is a collection of elements of any data type except mutable elements (such as lists, sets, dictionaries, etc.). However, no element can be repeated. The figure below shows examples of two sets, and .
Python’s built-in data type set()
and its helper functions can be leveraged to make sets and perform different operations on them. Union and intersection are the two of the most commonly performed operations on sets and can be found with the union()
and intersection()
functions.
For intersection of and , you can use the following syntax:
intersection_set = A.intersection(B)
For union:
union_set = A.union(B)
The intersection of two sets is the collection of elements that are present in both sets. In the example of sets and , we can see that the element is common in both. Hence, the intersection of and will be .
The program below prints the intersection of and .
def main ():set_A = set({1, 2, "hello"})set_B = set({2, 3, 10})set_intersection = set_A.intersection(set_B)print(set_intersection)main ()
The union of two sets is the set of all elements that are present in the two sets. In and , the collection of all elements is .
The Python program below shows how to find the union of two sets.
def main ():set_A = set({1, 2, "hello"})set_B = set({2, 3, 10})set_intersection = set_A.union(set_B)print(set_intersection)main ()