Generate a set of tuples containing numbers and their squares, but only for even numbers


This Python code uses a set comprehension to create a new set named even_num_squares, which contains tuples of even numbers and their squares from a list of numbers. Here's how the code works:

  • numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] : This line initializes a list named numbers with ten integer elements.
  • even_num_squares = {(x, x**2) for x in numbers if x % 2 == 0}: This line initializes the set even_num_squares using a set comprehension.
    • for x in numbers: This part of the code sets up a loop that iterates through each number in the numbers list.
    • if x % 2 == 0: This part of the code filters the numbers to include only even numbers (numbers that are divisible by 2).
    • (x, x**2): For each even number, this part creates a tuple containing the original number and its square.
  • print(numbers): This line of code prints the original list of numbers, numbers, to the console.
  • print(even_num_squares): This line of code prints the even_num_squares set to the console, containing tuples of even numbers and their squares.

Source Code

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_num_squares = {(x, x**2) for x in numbers if x % 2 == 0}
print(numbers)
print(even_num_squares)

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
{(2, 4), (4, 16), (8, 64), (10, 100), (6, 36)}

Example Programs