Generate a list of tuples containing numbers and their cubes


This Python code uses a list comprehension to generate pairs of numbers and their cubes for values of x ranging from 1 to 10. Here's how the code works:

  • num_cubes = [(x, x**3) for x in range(1, 11)]: This line of code initializes a variable named num_cubes and assigns it the result of a list comprehension.
    • for x in range(1, 11): This part sets up a loop that iterates through numbers from 1 to 10 (inclusive). It generates values for x.
    • (x, x**3): For each value of x, this expression creates a tuple containing two elements: the original value x and its cube, calculated as x**3.
    • [(x, x**3) for x in range(1, 11)]: This is the list comprehension itself. It iterates through the values of x in the specified range (1 to 10) and pairs each value with its cube, including these pairs (tuples) in the new list.
  • print(num_cubes): This line of code prints the num_cubes list to the console.

Source Code

num_cubes = [(x, x**3) for x in range(1, 11)]
print(num_cubes)

Output

[(1, 1), (2, 8), (3, 27), (4, 64), (5, 125), (6, 216), (7, 343), (8, 512), (9, 729), (10, 1000)]

Example Programs