Tuple of pairs of elements and their squares in Python


This Python code creates a tuple called squared_tuples, which contains pairs of numbers and their corresponding squares from the numbers list. Here's how the code works:

  • numbers = [1, 2, 3, 4, 5]: This line initializes a variable named numbers and assigns it a list containing five numbers.
  • squared_tuples = tuple((x, x**2) for x in numbers): This line of code initializes a variable named squared_tuples and assigns it a tuple created using a generator expression.
    • for x in numbers: This part of the code sets up a loop that iterates through each number x in the numbers list.
    • (x, x**2): For each number, it creates a tuple containing the number x and its square x**2.
    • tuple(...): This surrounds the generator expression and converts the generated pairs of numbers and their squares into a tuple.
  • print(numbers): This line of code prints the original numbers list to the console.
  • print(squared_tuples): This line of code prints the squared_tuples tuple (which contains pairs of numbers and their squares) to the console.

Source Code

numbers = [1, 2, 3, 4, 5]
squared_tuples = tuple((x, x**2) for x in numbers)
print(numbers)
print(squared_tuples)

Output

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

Example Programs