← Practice
πŸ“– ComprehensionsLearning path
Browsing as guestΒ·Sign in or create a free account to save progress and use tutor tools.
LessonΒ·difficulty 2/5Β·~10 min

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 + 10 for n in nums]        # [11, 12, 13, 14]  β€” transform every item
[n for n in nums if n > 2]    # [3, 4]             β€” keep only some items

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: a single comprehension can filter and transform at once β€” keep the numbers that pass your even-test, and square each one that survives.

Tests

  • mixed small list
  • all even
  • empty input
  • no evens

✦ Stuck? Ask for a spark

Sign in or create a free account to use your monthly AI explainer allowance.

warming up
Loading editor…
Consolewaiting

$ Console output will appear here.

>_AI coach
Sign in or create a free account to chat with the tutor.