Skip to content

List comprehensions

Read and write a list comprehension with an optional condition, and rewrite a loop that builds or filters a list as one.

It opens on

Two programs square nums = [3, 1, 4], one with a loop and append, one in a single line inside square brackets. Does the one-liner print [9, 1, 16] or a single number?

Why it matters

Building a new list from an old one, squaring the numbers, keeping the long words, dropping the bad readings, is the commonest job a list has, and Python programmers write it in one line; reading that line fluently also means knowing where its if goes.

Good to know first

  • Traversing lists: a for loop visits each item and append builds a new list
  • Lists: indexing and mutation: append changes a list and returns None
  • Loops: a for loop variable takes each value in turn

Step by step

  1. A loop in one line

    Write the comprehension for a loop that appends an expression of each item, and read one aloud.

    n is 3, then 1, then 4, so the loop appends 9, then 1, then 16, and the program prints [9, 1, 16].

    A common mix-up

    A comprehension changes the list it loops over, or builds one number.

    In fact: It builds a new list with one result per item and leaves the old list as it was.

  2. Keep only some items

    Rewrite a loop with an if around append as a comprehension with the if at the end, and trace which items it keeps.

    For n = 4, n % 2 == 0 is True, so 16 is appended. For n = 9 the test is False, so nothing is appended, and the loop goes on to the next item.

    the first two items

    A common mix-up

    The if at the end changes the items that pass it, or leaves a gap for the others.

    In fact: It only chooses; failing items add nothing, so the new list is shorter.

  3. The if at the front, and when to keep the loop

    Tell an if at the end, which filters, from n if n > 0 else 0 at the front, which chooses a value, and decide when a plain loop reads better.

    The first is the filter from before. It keeps n only when n > 0, so it keeps 4, 2 and 6 and prints [4, 2, 6].

    A common mix-up

    If and else can follow the for part like the end if.

    In fact: At the end only a plain if is allowed; a choice of value goes at the front.

Try it

What does [k * 2 for k in [5, 6, 7]] build?Answer

[10, 12, 14]

Hint: One result for each k

Rewrite as one line, for xs = [7, 2, 9, 4], the loop that appends x + 1 only when x > 3.Answer

[x + 1 for x in xs if x > 3]

Hint: Expression, for part, if part

Write one line that turns xs = [3, -5, 8] into [3, 0, 8], zeros for the negatives.Answer

[x if x >= 0 else 0 for x in xs]

Hint: Every item stays, so the choice goes at the front

What list does [n + 10 for n in nums] build?Answer

[13, 11, 14], one result for each of the three items.

What happens for n = 2 and then for n = 7?Answer

2 is even so 4 is appended; 7 is odd so nothing is appended.

List comprehensions

30 minutes every month. No card.