Return A New Set Of Identical Items From Two Sets In Python
Chapter:
Python
Last Updated:
19-05-2023 03:14:50 UTC
Program:
/* ............... START ............... */
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
common_elements = set1.intersection(set2)
print(common_elements)
/* ............... END ............... */
Output
Notes:
-
In the given program, we have two sets: set1 and set2. The intersection() method is used to find the common elements between these two sets.
- The intersection() method compares the elements of set1 with the elements of set2 and returns a new set that contains only the elements present in both sets.
- In this case, set1 contains the elements {1, 2, 3, 4, 5} and set2 contains the elements {4, 5, 6, 7, 8}. When we call set1.intersection(set2), it checks for the common elements between the two sets and returns a new set {4, 5}.
- Finally, we print the common_elements set, which outputs {4, 5} as these are the elements that are present in both set1 and set2.