Sub topic 15
From for loops to list comprehensions
This chapter assumes you can write a basic for loop, call range(), and use if statements and lists.
The loop pattern that comprehensions replace
A common job is to build a new list from an old iterable. With a plain loop, you start with an empty list and append to it:
squares = []
for n in range(1, 6):
squares.append(n * n)
print(squares) # [1, 4, 9, 16, 25]A list comprehension does the same job in one expression:
squares = [n * n for n in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]The expression n * n is what goes into the list. The for n in range(1, 6) part is the same loop header you already know.
Adding a filter
To keep only some items, put an if clause at the end. It works like an if inside the loop body.
evens = [n for n in range(10) if n % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]If you want to choose between two values instead of dropping items, use a conditional expression at the front:
labels = ["even" if n % 2 == 0 else "odd" for n in range(4)]
print(labels) # ['even', 'odd', 'even', 'odd']The trailing if filters items. The if ... else at the front picks a value for each item.
Nested loops in a comprehension
Several for clauses read in the same order as nested loops, with the outer loop first:
pairs = [(i, j) for i in range(1, 3) for j in range(1, 3)]
print(pairs) # [(1, 1), (1, 2), (2, 1), (2, 2)]Common errors
- Using a comprehension for side effects. Writing
[print(n) for n in range(3)]builds a throwaway list ofNonevalues. Use a normalforloop when you only want an action. - Cramming in too much. If you need more than one
forclause plus a condition, a regular loop is usually easier to read. - Expecting laziness. A list comprehension builds the whole list immediately. For large ranges that you only need to total or scan once, use a generator expression, which has parentheses and builds items on demand:
total = sum(n * n for n in range(1_000_000))
print(total) # 333332833333500000- Worrying about the loop variable. In Python 3, the variable inside a comprehension does not leak into the surrounding scope. This differs from a
forstatement, where the variable stays bound after the loop.
for i in range(3):
pass
print(i) # 2
[k for k in range(3)]
# print(k) would raise NameErrorThe same syntax with braces builds sets and dictionaries, for example {n: n * n for n in range(3)} gives {0: 0, 1: 1, 2: 4}.
Exercise
Rewrite this loop as a list comprehension. words = ["tree", "sun", "river", "sky"] short = [] for w in words: if len(w) <= 3: short.append(w.upper())
Show answer
short = [w.upper() for w in words if len(w) <= 3]. The result is ['SUN', 'SKY']. The expression w.upper() comes first, then the for clause, then the filter.