Sub topic 10
Building lists with comprehensions
This chapter assumes you can write a for loop with an if statement, and that you know how to build a list with append. A list comprehension is a compact expression that builds a new list from any iterable.
From loop to comprehension
This loop collects the squares of the even numbers below 6:
squares = []
for n in range(6):
if n % 2 == 0:
squares.append(n * n)
print(squares) # [0, 4, 16]The comprehension below does the same job in one expression:
squares = [n * n for n in range(6) if n % 2 == 0]
print(squares) # [0, 4, 16]The comprehension has three parts, in this order:
- The expression to store (
n * n). - The
forclause that supplies items (for n in range(6)). - An optional
ifclause that filters items (if n % 2 == 0).
The comprehension always returns a new list. It never changes the source iterable.
Filtering versus choosing a value
An if placed after the for clause removes items. An if/else placed before the for clause is a conditional expression. It keeps every item and picks a value for each one:
labels = ["even" if n % 2 == 0 else "odd" for n in range(4)]
print(labels) # ['even', 'odd', 'even', 'odd']
evens = [n for n in range(4) if n % 2 == 0]
print(evens) # [0, 2]A filter cannot have an else. If you need one, move the condition to the front.
Multiple loops
You can chain several for clauses. They nest in the same order you would write the loops:
pairs = [(x, y) for x in range(2) for y in range(3)]
print(pairs) # [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [value for row in matrix for value in row]
print(flat) # [1, 2, 3, 4, 5, 6]Read flat left to right as "for each row in matrix, for each value in row". The leftmost for is the outer loop.
Comprehensions and nested lists
A comprehension is the right way to build a grid, because the expression runs once per row and creates a separate inner list each time:
grid = [[0] * 3 for _ in range(2)]
grid[0][0] = 1
print(grid) # [[1, 0, 0], [0, 0, 0]]Writing [[0] * 3] * 2 instead repeats a reference to one inner list. Changing one row then changes both.
Common errors
- Using a comprehension for side effects.
[print(n) for n in nums]builds a throwaway list ofNonevalues. Use a plainforloop when you do not need the result. - Unreadable nesting. If a comprehension needs more than one filter and more than two
forclauses, a regular loop is clearer. - Expecting the loop variable to leak. In Python 3,
nexists only inside the comprehension. It does not overwrite a variable namednoutside it. - Building a huge list you only loop over once. If you only need to iterate, or to pass the values to
sumormax, use a generator expression with parentheses:sum(n * n for n in range(1000000)). It produces items one at a time and does not store them all.
Exercise
Given words = ["pear", "fig", "banana", "kiwi"], write a comprehension that produces the lengths of only those words longer than 3 characters. What does it return?
Show answer
lengths = [len(w) for w in words if len(w) > 3] returns [4, 6, 4]. The filter drops "fig", and the expression len(w) is stored for each remaining word.