Comprehensions
Last updated
Many loops do the same job: start with an empty list, loop, and append. In this lesson you'll write that kind of loop in one line, as a list comprehension, keep only some items with if, build a dictionary the same way, and learn when a plain loop is still the better choice.
By the end of this lesson you can
- Build a list from another list with a list comprehension
- Keep only some items by adding
ifto a comprehension - Build a dictionary with a dict comprehension
- Choose between a comprehension and a loop, and spot round brackets used by mistake
A loop in one line
You've written this kind of loop several times: make an empty list, loop over another list, and .append() something each round. Lines 4 to 7 do that, building a list of title lengths.
Line 10 builds the same list with a list comprehension. Read it from the middle: for each t in titles, put len(t) in the new list. The square brackets say the result is a list.
Watch it run. The comprehension on line 10 runs as one line, but Python still goes round once for each title. It's the same loop, written shorter.
Keeping only some items
Add if at the end, and only the items that pass the test go into the new list. Line 2 keeps the days that are more than 0, so the books returned on time drop out.
Line 4 does both jobs at once: it keeps only the late loans and works out a fine for each. sum() adds up all the numbers in a list.
Read a comprehension in this order: the loop (for d in days_late), then the test (if d > 0), then the value at the front (d * 25), which is what goes in the list.
Dict comprehensions
With curly brackets and a key: value pair at the front, a comprehension builds a dictionary instead of a list. Line 2 maps each title to its length.
Line 6 loops over a dictionary with .items(), from lesson 2.2, and keeps only the members who owe something.
You can also build a set with curly brackets and a single value at the front, like {t[0] for t in titles}, the first letters with no repeats.
When a loop reads better
A comprehension is for one job: building a list or a dictionary. When each round has to do several things, like work out a fine, add it to a total and print a line, a plain for loop is clearer.
Don't use a comprehension just to run something, like [print(t) for t in titles]. It works, but it builds a list nobody wants, and readers expect a comprehension to make a value. If a comprehension grows past one line, or needs a second for, write the loop instead.
Round brackets
This program is meant to print the titles in capitals, as a list. Someone used round brackets instead of square ones. Press Run and look at what comes out.
There's no tuple comprehension. Round brackets make a generator, which is useful when the values go straight into something like sum(): sum(d * 25 for d in days_late) adds the fines without building a list first. You'll meet generators properly in Stage 4. For now, when you want a list, use square brackets.
Check what you learned
Four questions. Pick or type an answer, then check it.
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- The Python Tutorial: List Comprehensions
- The Python Tutorial: Dictionaries: dict comprehensions, near the end of the section
- The Python Language Reference: Displays for lists, sets and dictionaries: the exact rules for comprehensions
- The Python Language Reference: Generator expressions: what round brackets make instead
- Built-in Functions: sum
- PEP 202: List Comprehensions
- PEP 274: Dict Comprehensions