Generate a list of tuples containing numbers and their squares


This Python code creates a list called num_squares using a list comprehension to generate pairs of numbers and their squares. Here's how the code works:

  • num_squares = [(x, x**2) for x in range(1, 11)]: This line of code initializes a variable named num_squares 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**2): For each value of x, this expression creates a tuple containing two elements: the original value x and its square, calculated as x**2.
    • [(x, x**2) for x in range(1, 11)]: This is the list comprehension itself. It iterates through the numbers in the specified range (1 to 10) and pairs each number with its square, including these pairs (tuples) in the new list.
  • print(num_squares): This line of code prints the num_squares list to the console.

Source Code

num_squares = [(x, x**2) for x in range(1, 11)]
print(num_squares)

Output

[(1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49), (8, 64), (9, 81), (10, 100)]

Example Programs