← All lessons

Lesson 09

List Comprehensions

A list comprehension creates a list in one readable expression.

The pattern is [expression for item in sequence]. Python computes the expression for each item.

Add a condition to keep only matching items: [n for n in numbers if n > 0].

numbers = [1, 2, 3, 4, 5, 6]
squares = [n * n for n in numbers]
evens = [n for n in numbers if n % 2 == 0]

print(squares)
print(evens)

Check your understanding

What is [n * 2 for n in range(3)]?

CHALLENGE

Create a list of squares of 1 through 4 using a comprehension, then print it.

Practice →
Next: Mini Project: Grade Report →