Generate a list of tuples containing a number and its square


This Python code creates a list called num_squares using a list comprehension to generate pairs of numbers and their squares for values of x ranging from 1 to 5. Here's how the code works:

  • num_squares = [(x, x**2) for x in range(1, 6)]: This line of code initializes a variable named num_squares and assigns it the result of a list comprehension.
    • for x in range(1, 6): This part sets up a loop that iterates through values of x from 1 to 5 (inclusive). The range(1, 6) function generates a sequence of numbers starting from 1 and ending at 5.
    • (x, x**2): For each value of x in the range, this expression creates a tuple containing two elements: the original value x and its square x**2.
    • [(x, x**2) for x in range(1, 6)]: This is the list comprehension itself. It iterates through the values of x in the specified range (1 to 5) and, for each value, generates a tuple containing x and x**2. These tuples are collected into a 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, 6)]
print(num_squares)

Output

[(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

Example Programs