← Practice
πŸ“– Comprehensionscomprehensions-even-squares
LessonΒ·difficulty 2/5Β·~10 min

Comprehensions: squares of evens

Comprehensions: squares of evens

A list comprehension builds a new list in one expressive line. It pairs a transform with an optional filter:

python
nums = [1, 2, 3, 4]
[n * n for n in nums]            # [1, 4, 9, 16]  β€” transform every item
[n for n in nums if n % 2 == 0]  # [2, 4]          β€” keep only the evens

You can do both at once: transform the items that pass the filter.

Your task

Write even_squares(nums) that returns a list of the squares of the even numbers in nums, keeping the original order.

python
even_squares([1, 2, 3, 4])   # [4, 16]
even_squares([2, 4, 6])       # [4, 16, 36]
even_squares([])              # []

Hint: [n * n for n in nums if n % 2 == 0] filters first, then squares.

Tests

  • mixed small list
  • all even
  • empty input
  • no evens
  • negatives and zero (hidden)
  • order preserved (hidden)

✦ Stuck? Ask for a spark

warming up
Loading editor…

$ Console output will appear here.

>_AI tutor
Sign in to chat with the tutor.