Bigger programs · lesson 4 of 12
Parts in this lesson
A[x for x in items]a list comprehension
Bif x > 0keeps only some items
C{k: v for ...}a dict comprehension
Dsum()adds up a list
E(x for x in items)not a list: a generator

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 if to 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.

Step 1 code main.py
Edit the code, then run it again

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.

Step 2 code main.py
Edit the code, then run it again

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.

Step 3 code main.py
Edit the code, then run it again

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.

Step 4 code main.py
Edit the code, then run it again

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.

Step 5 code main.py
Edit the code, then run it again

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.

What does this program print?
pages = [120, 75, 300, 42]
long = [p // 10 for p in pages if p > 100]
print(long)
Which line makes {"Dune": 4, "Emma": 4} from titles = ["Dune", "Emma"]?
Each round needs to work out a fine, add it to a total and print a line. What should you write?
What does (n * 2 for n in [1, 2, 3]) make?

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.

All sources for Simple Python