Generating pairs of elements from two sets


This Python code creates pairs of elements from two sets, set1 and set2, and stores these pairs in a new set called pairs. Here's how the code works:

  • set1 = {1, 2, 3}: This line initializes a set named set1 containing three integers.
  • set2 = {"a", "b", "c"}: This line initializes another set named set2 containing three strings.
  • pairs = {(x, y) for x in set1 for y in set2}: This line uses a set comprehension to create pairs of elements from set1 and set2.
    • for x in set1: This part of the code iterates through each element in set1.
    • for y in set2: For each element in set1, it iterates through each element in `set2, creating pairs (x, y) for all combinations.
  • print(set1): This line prints the original set1 to the console.
  • print(set2): This line prints the original set2 to the console.
  • print(pairs): This line prints the pairs set (which contains all possible pairs of elements from set1 and `set2) to the console.

Source Code

set1 = {1, 2, 3}
set2 = {"a", "b", "c"}
pairs = {(x, y) for x in set1 for y in set2}
print(set1)
print(set2)
print(pairs)

Output

{1, 2, 3}
{'b', 'c', 'a'}
{(2, 'b'), (3, 'a'), (3, 'b'), (1, 'b'), (1, 'a'), (2, 'c'), (3, 'c'), (1, 'c'), (2, 'a')}

Example Programs