Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.
List Comprehensions
A list comprehension is a compact way to build a list from another list. These two are identical:
result = []
for n in numbers:
result.append(n * 2)result = [n * 2 for n in numbers]
Read it left to right as "the doubled n, for each n in numbers".
You can filter at the same time by adding if on the end:
[n for n in numbers if n > 0] # keep only the positives [n * 2 for n in numbers if n % 2 == 0] # double only the even ones
Comprehensions are idiomatic Python and you will read them constantly. They stop being a good idea when they get long: if you need two conditions and a nested loop, a normal for loop is clearer, and clearer wins.
Your task:
Write squares_of_evens(numbers) that returns the squares of only the even numbers, in the order they appeared.
[1, 2, 3, 4] returns [4, 16], because 2 and 4 are even and their squares are 4 and 16.
Example Tests
Only the even numbers are squared
Input: {"numbers":[1,2,3,4]}
Expected: [4,16]
All-odd input gives an empty list
Input: {"numbers":[1,3,5]}
Expected: []
Zero is even, and its square is 0
Input: {"numbers":[0,1,2]}
Expected: [0,4]
def squares_of_evens(numbers):
"""
Square the even numbers and ignore the odd ones.
Args:
numbers: a list of whole numbers
Returns:
A list of the squares of the even numbers, in the original order.
"""
# YOUR CODE HERE
passRun your code to see results
⌘↵ runs against the visible tests