Generate a list of numbers with their squares if the number is even


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

  • numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: This line initializes a variable named numbers and assigns it a list containing numbers from 1 to 10.
  • squared_evens = [x**2 for x in numbers if x % 2 == 0]: This line of code initializes a variable named squared_evens and assigns it the result of a list comprehension.
    • for x in numbers: This part sets up a loop that iterates through each number in the numbers list.
    • if x % 2 == 0: This condition checks whether the current number x is even. If it is even (i.e., its remainder when divided by 2 is 0), it proceeds to the next part.
    • x**2: For each even number, this expression calculates its square (x**2).
    • [x**2 for x in numbers if x % 2 == 0]: This is the list comprehension itself. It iterates through the numbers in the numbers list and, for each even number, calculates its square and includes it in the new list.
  • print(numbers): This line of code prints the original numbers list to the console.
  • print(squared_evens): This line of code prints the squared_evens list to the console.

Source Code

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squared_evens = [x**2 for x in numbers if x % 2 == 0]
print(numbers)
print(squared_evens)

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[4, 16, 36, 64, 100]

Example Programs