Python List Comprehension Practice: Even Squares
A list comprehension builds a new list from an existing one in a single expression. It can transform each value and filter values at the same time. This exercise combines both ideas: select the even numbers, then square them.
Before you start: Lists, for loops and the remainder operator.
Your task
Use a list comprehension to build a list containing the square of every even number. Print the list.
Starter code
numbers = [1, 2, 3, 4, 5, 6]
# Build a list of the squares of the even numbers, then print it.
Expected result
[4, 16, 36]Loads the starter in the workspace. Save or export existing work first. Return here for hints and the explanation.
Need a hint?
Write [expression for n in numbers if condition]. The condition checks whether n % 2 equals 0.
Show the complete solution and walkthrough
numbers = [1, 2, 3, 4, 5, 6]
# Build a list of the squares of the even numbers, then print it.
even_squares = [n * n for n in numbers if n % 2 == 0]
print(even_squares)
- Start with the loop part: for n in numbers. Each number from the list is assigned to n in turn.
- Add the filter if n % 2 == 0. Only 2, 4 and 6 reach the expression at the front.
- Use n * n as the expression. Printing the new list shows [4, 16, 36].
A common mistake
Putting the condition in the wrong place changes the meaning. A trailing if filters values, while a conditional expression at the front transforms every value.
Try an edge case
If no number is even, the result is an empty list. Negative even numbers also pass the test, because -4 % 2 is 0 in Python.
Take it one step further
Write the same logic as a for loop with append, then compare the two versions. Try a comprehension that returns the uppercase form of words longer than three letters.