Exercises
List Comprehension
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Rewrite this loop as a single comprehension.
Python
squares = []
for n in range(5):
squares.append(n ** 2)
print(squares)What to collect, then where it comes from.
squares = [n ** 2 for n in range(5)]
print(squares)Exercise 2Passed
Keep only the even numbers, using a comprehension.
Python
numbers = [1, 2, 3, 4, 5, 6]
# build a list of the even ones
A filtering if goes at the end.
numbers = [1, 2, 3, 4, 5, 6]
evens = [n for n in numbers if n % 2 == 0]
print(evens)Exercise 3Passed
Label each number even or odd, keeping all four.
Python
numbers = [1, 2, 3, 4]
# build ['odd', 'even', 'odd', 'even']
An if/else that chooses a value goes at the front, before the for.
numbers = [1, 2, 3, 4]
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(labels)