Generate a list of squares of even numbers from 1 to 20


This Python code creates a list called even_squares using a list comprehension to calculate the square of even numbers from 2 to 20. Here's how the code works:

  • even_squares = [x**2 for x in range(2, 21, 2)]: This line of code initializes a variable named even_squares and assigns it the result of a list comprehension.
    • for x in range(2, 21, 2): This part sets up a loop that iterates through even numbers from 2 to 20 (inclusive). The range(2, 21, 2) function generates a sequence of even numbers starting from 2 and ending at 20, with a step size of 2.
    • x**2: For each even number, this expression calculates its square (x**2).
    • [x**2 for x in range(2, 21, 2)]: This is the list comprehension itself. It iterates through the even numbers in the specified range and, for each even number, calculates its square and includes it in the new list.
  • print(even_squares): This line of code prints the even_squares list to the console.

Source Code

even_squares = [x**2 for x in range(2, 21, 2)]
print(even_squares)

Output

[4, 16, 36, 64, 100, 144, 196, 256, 324, 400]

Example Programs