Generate a set of common elements from multiple sets


In this Python code, you have three sets: set1, set2, and set3, and you are finding the common elements that are present in all three sets. Here's how the code works:

  • set1 = {1, 2, 3, 4, 5}: This line defines set1 as a set containing the elements 1, 2, 3, 4, and 5.
  • set2 = {3, 4, 5, 6, 7}: This line defines set2 as a set containing the elements 3, 4, 5, 6, and 7.
  • set3 = {5, 6, 7, 8, 9}: This line defines set3 as a set containing the elements 5, 6, 7, 8, and 9.
  • common_elements = {x for x in set1 if x in set2 and x in set3}: This line creates a set named common_elements using a set comprehension. It iterates through the elements in set1 and includes an element in the common_elements set if it is also present in both set2 and set3. In other words, it finds the elements that are common to all three sets.
  • print(set1): This line prints the set1 set to the console.
  • print(set2): This line prints the set2 set to the console.
  • print(set3): This line prints the set3 set to the console.
  • print(common_elements): This line prints the common_elements set to the console.

Source Code

set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
set3 = {5, 6, 7, 8, 9}
common_elements = {x for x in set1 if x in set2 and x in set3}
print(set1)
print(set2)
print(set3)
print(common_elements)

Output

{1, 2, 3, 4, 5}
{3, 4, 5, 6, 7}
{5, 6, 7, 8, 9}
{5}

Example Programs