Sub topic 1
From a for loop to a comprehension
Prerequisites
Assume you know Python for loops, range, lists, Boolean expressions, and the append method. A comprehension is a compact expression that builds a collection from an iterable, such as a list or range.
From a for loop to a comprehension
Start with a loop that transforms each item:
squares = []
for n in range(5):
squares.append(n * n)
print(squares)The equivalent list comprehension is:
squares = [n * n for n in range(5)]
print(squares)Both versions produce [0, 1, 4, 9, 16]. Read the comprehension from left to right: calculate n * n for each n in range(5).
Filtering items with an `if` clause
Put a trailing if after the for clause to keep only matching items:
even_squares = [n * n for n in range(10) if n % 2 == 0]
print(even_squares)The result is [0, 4, 16, 36, 64]. The condition filters items before the output expression is added.
The equivalent loop is:
even_squares = []
for n in range(10):
if n % 2 == 0:
even_squares.append(n * n)Choosing values with `if/else` in the output expression
Use a conditional expression before for when every input item should produce a value:
labels = [
"even" if n % 2 == 0 else "odd"
for n in range(5)
]
print(labels)This produces ['even', 'odd', 'even', 'odd', 'even']. The if/else chooses the output for each item, while a trailing if decides whether an item is included.
Exercise
Write a comprehension that contains the cubes of odd numbers from 0 through 9.
Show answer
cubes = [n ** 3 for n in range(10) if n % 2 == 1]