21. Squares of the evens
Write a function even_squares(numbers) that takes a list of whole numbers and returns a new list with the square of
each even number, in the order they appear. Leave out the odd numbers. The square of a number is the number times
itself: the square of 4 is 16.
A number is even when it divides by 2 with nothing left over. That includes 0 and negative numbers such as -4. If
there are no even numbers, or the list is empty, return an empty list [].
Try to write it in one line, with a list comprehension.
Example 1
numbers = [1, 2, 3, 4][4, 16]Example 2
numbers = [5, 7][]Example 3
numbers = [-4, 0, 9][16, 0]Constraints
numbershas 0 to 100 items.- Each item is a whole number from -1000 to 1000.
Submit also runs 3 more tests you can't see.
Practises List Comprehensions (lesson 15).
n % 2 == 0isTruefor an even number, and that includes 0 and negative ones such as -4.- A comprehension can filter:
[... for n in numbers if ...]keeps only the items whose test isTrue, and gives[]when none pass. - Put what to keep in front and the test at the end:
[n * n for n in numbers if ...].
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def even_squares(numbers):
"""Square the even numbers of a list.
numbers: list of int; may be empty
Returns: list of int, the squares of the even
numbers, in order
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.