Generate a set of tuples containing numbers and their squares


This Python code uses a set comprehension to create a set named num_squares that contains tuples with pairs of numbers and their squares. Here's how the code works:

  • {(x, x**2) for x in range(1, 6)}: This set comprehension creates a set by iterating through the values of x from 1 to 5 (inclusive). For each value of x, it generates a tuple (x, x**2) containing the original number x and its square x**2. The result is a set of these tuples.
  • print(num_squares): This line of code prints the num_squares set to the console.

Source Code

num_squares = {(x, x**2) for x in range(1, 6)}
print(num_squares)

Output

{(2, 4), (4, 16), (1, 1), (3, 9), (5, 25)}

Example Programs