Create a List of Squares of numbers from 1 to 10


The code you provided is written in Python and uses a list comprehension to create a list called squares that contains the squares of numbers from 1 to 10. Here's a step-by-step explanation of the code:

  • squares = [x**2 for x in range(1, 11)]: This line of code initializes a variable named 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). The range(1, 11) function generates a sequence of numbers starting from 1 and ending at 10.
    • x**2: For each value of x in the range, this expression calculates the square of 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, for each number, calculates its square. The resulting squares are collected into a new list.
  • print(squares): This line of code simply prints the squares list to the console.

Source Code

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

Output

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Example Programs