Chapters
Python114 chapters

Exercises

List Comprehension

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

Rewrite this loop as a single comprehension.

Python
squares = []
for n in range(5):
    squares.append(n ** 2)
print(squares)
Exercise 2

Keep only the even numbers, using a comprehension.

Python
numbers = [1, 2, 3, 4, 5, 6]
# build a list of the even ones
Exercise 3

Label each number even or odd, keeping all four.

Python
numbers = [1, 2, 3, 4]
# build ['odd', 'even', 'odd', 'even']