Squares of numbers from 1 to 10 as tuples in Python


This Python code generates a tuple called squares using a generator expression. The tuple contains the squares of numbers from 1 to 10. Here's how the code works:

  • squares = tuple(x**2 for x in range(1, 11)): This line of code initializes a variable named squares and assigns it a tuple created using a generator expression.
    • x**2 for x in range(1, 11): This part of the code uses a generator expression to generate the squares of numbers from 1 to 10.
      • for x in range(1, 11): This sets up a loop that iterates through numbers from 1 to 10 using the range(1, 11) iterable.
      • x**2: For each value of x in the range, it calculates the square of x using the x**2 expression.
    • tuple(...): This surrounds the generator expression and converts the generated values into a tuple.
  • print(squares): This line of code prints the squares tuple to the console.

Source Code

squares = tuple(x**2 for x in range(1, 11))
print(squares)

Output

(1, 4, 9, 16, 25, 36, 49, 64, 81, 100)

Example Programs