This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 5: List comprehension

List comprehension exercise

face Josiah Wang

Here is an exercise.

Convert the following piece of code to use list comprehension instead.

numbers = []
for i in range(50):
    if i%2 == 0 and i%3 == 0:
        numbers.append(i*i)
print(numbers)

No peeking at the solutions until you have tried it! 👀

A possible solution:

numbers = [i*i for i in range(50) if i%2 == 0 and i%3 == 0]
print(numbers)

Alternative solution:

numbers = [i*i for i in range(50) if i%2 == 0 if i%3 == 0]
print(numbers)