Generate a set of tuples containing numbers and their cubes


This Python code uses a set comprehension to create a new set named num_cubes. It contains pairs of numbers where the first number (x) is in the range from 1 to 5, and the second number is the cube of x. Here's how the code works:

  • {(x, x**3) for x in range(1, 6)}: This is a set comprehension that creates pairs (x, x**3) for x in the range of numbers from 1 to 5.
    • for x in range(1, 6): This part of the code sets up the loop, iterating through numbers from 1 to 5 (inclusive).
    • (x, x**3): For each value of x, it creates a tuple containing the value of x and its cube, x**3.
  • print(num_cubes): This line of code prints the num_cubes set to the console.

Source Code

num_cubes = {(x, x**3) for x in range(1, 6)}
print(num_cubes)

Output

{(3, 27), (4, 64), (1, 1), (5, 125), (2, 8)}

Example Programs