Sub topic 1
From a for loop to a comprehension
A list comprehension builds a new list from an existing iterable in a single expression. This chapter shows how to turn a loop that builds a list into a comprehension, and how to read one.
Prerequisites
This chapter assumes you know:
- How to write a
forloop and userange. - How lists, dictionaries, and sets work as built-in types.
- How to call
appendon a list. - How basic comparisons and boolean expressions work.
The loop you already know
Many loops follow the same pattern. They create an empty list, visit each item, and append one result per item:
squares = []
for n in range(10):
squares.append(n * n)
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]This works, but three lines carry one idea: "the square of every n". A comprehension states that idea directly:
squares = [n * n for n in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]Both versions produce the same list.
The conversion recipe
You can convert a loop mechanically in three steps.
- Delete the line that creates the empty list. The square brackets of the comprehension create the list instead.
- Take the expression passed to
appendand write it first, inside the brackets. - Copy the
forline after it, without its trailing colon.
The diagram shows where each part of the loop ends up.
Read the result from left to right as a sentence: "give me n * n for each n in range(10)." The output expression comes first because it is the value that ends up in the list. The for clause says where the values come from.
Any iterable works
The source does not have to be range. A comprehension can loop over a list, a string, a file, or anything else that a for loop accepts. The output expression can be any expression, including a method call:
names = ["ada", "grace", "linus"]
upper = [name.upper() for name in names]
print(upper) # ['ADA', 'GRACE', 'LINUS']
letters = [ch for ch in "abc"]
print(letters) # ['a', 'b', 'c']The comprehension does not change names. It evaluates to a new list, and you decide what to do with it, usually by assigning it to a name.
Common errors
Most mistakes at this stage come from keeping habits from the loop version.
- Keeping the colon.
[n * n for n in range(10):]is aSyntaxError. Theforclause has no colon. - Putting the
forfirst.[for n in range(10) n * n]is also aSyntaxError. The output expression must come first. - Calling
appendinside the comprehension.appendreturnsNone, so you would build a list ofNonevalues and throw it away:
result = []
junk = [result.append(n * n) for n in range(3)]
print(result) # [0, 1, 4]
print(junk) # [None, None, None]This "works" only through a side effect, and it wastes memory on the throwaway list. If you want a side effect, use a plain loop. If you want a list, write the output expression directly.
- Using the wrong brackets. Square brackets build a list. Parentheses build a generator expression, which is a different object covered in a later chapter.
What stays the same
The comprehension does the same work as the loop. It visits the same items in the same order, and it evaluates the output expression once per item. It is not a different algorithm, and for simple cases the speed difference is small, though a comprehension is usually a little faster than repeated append calls. Choose it for clarity: one line that says what the list contains is easier to scan than three lines that build it step by step.
Later chapters add to this pattern. An if clause filters items, an if/else in the output expression chooses values, and swapping the brackets gives you a dict or a set. Each one extends the same three-part structure you just learned.
Exercise
Convert this loop into a list comprehension. lengths = [] for word in ["sun", "moon", "star"]: lengths.append(len(word))
Show answer
lengths = [len(word) for word in ["sun", "moon", "star"]]
The append argument len(word) becomes the output expression, the for line follows it without the colon, and the brackets replace lengths = []. The result is [3, 4, 4].
Exercise
What does data contain after this code runs, and why is it a poor way to build a list?
data = []
[data.append(i) for i in range(3)]
Show answer
data is [0, 1, 2], but only because append modifies it as a side effect. The comprehension itself builds a throwaway list [None, None, None], because append returns None. Write data = [i for i in range(3)] instead.