List Comprehensions — Python

A list comprehension [expression for item in iterable] builds a new list in one line and does not change the original list. For example, [p + 2 for p in…

Every price on the menu goes up by $2. With a for loop, building the new price list takes three lines: make an empty list, go through the old list, and add each new price with append. Python has a way to write the same thing in one line: [p + 2 for p in prices].

That form is called a list comprehension: a way to build a new list from another list. It takes each item, can filter it first with if, then turns it into a new value. It works like Mr. Darto copying the old price list onto a new sheet of paper and adding $2 on every line. If he only wants the cheap items, he skips the expensive ones. He never crosses out the old sheet (the old list): the result is always a new sheet (the new list).

From a for loop to a comprehension

With the for loop from an earlier lesson, raising every price takes three lines, lines 2 to 4:

prices = [15, 5, 12]
raised = []
for p in prices:
    raised.append(p + 2)
print(raised)   # [17, 7, 14]

A list comprehension writes the same thing in one line, line 2:

prices = [15, 5, 12]
raised = [p + 2 for p in prices]
print(raised)   # [17, 7, 14]
print(prices)   # [15, 5, 12]

Filtering with if

Add if condition at the back to filter the items:

prices = [15, 5, 12]
cheap = [p for p in prices if p < 13]
print(cheap)                                    # [5, 12]
print([p + 2 for p in prices if p < 13])        # [7, 14]

On the second line, the expression is only p: an item that passes goes in unchanged. This table follows the last line, item by item:

p p < 13 What goes into the new list
15 False skipped
5 True 5 + 2 = 7
12 True 12 + 2 = 14

With range from the for loop lesson, a comprehension can build a series of numbers. range(6) is 0 to 5, and x % 2 == 0 means x is even:

print([x * 3 for x in range(6) if x % 2 == 0])           # [0, 6, 12]
print([x ** 2 for x in range(1, 6)])                     # [1, 4, 9, 16, 25]

Changing text

A comprehension also works on a list of text:

orders = ["coffee with milk", "sweet tea", "toast"]

print([m.upper() for m in orders])              # ['COFFEE WITH MILK', 'SWEET TEA', 'TOAST']
print([len(m) for m in orders])                 # [16, 9, 5]
print([m.upper() for m in orders if "a" in m])  # ['SWEET TEA', 'TOAST']

📌 Choosing a value with if-else

An if at the back filters. When you want every item to stay, with its value chosen from two options, write if ... else at the front, before the for, as part of the expression (the one-line if from the if lesson):

prices = [15, 5, 12]
label = ["cheap" if p < 10 else "pricey" for p in prices]
print(label)   # ['pricey', 'cheap', 'pricey']

Each price gets a label: cheap when it is under 10, pricey otherwise. The position of the if decides its meaning: at the back it filters, at the front it chooses a value. Python refuses an else at the back, and does not run a single line:

  File "/home/darto/stall.py", line 2
    result = [p for p in prices if p < 10 else 0]
                                             ^^^^
SyntaxError: invalid syntax

📌 Dictionary comprehensions

With curly braces and key: value, the result is a dictionary:

orders = ["coffee with milk", "sweet tea", "toast"]
print({m: len(m) for m in orders})   # {'coffee with milk': 16, 'sweet tea': 9, 'toast': 5}

Curly braces without a colon, like {p + 2 for p in prices}, make a set.

⚠️ else at the back, p outside, and a range that stops one early

TL;DR: A list comprehension [expression for item in iterable] builds a new list in one line and does not change the original list. For example, [p + 2 for p in prices] adds 2 to each p in the list prices. In that example p + 2 is the expression, and prices is the iterable (what the for goes through). Add if condition at the back to filter: items whose condition is False are skipped. With prices = [15, 5, 12], [p + 2 for p in prices if p < 13] is [7, 14]. Another example: [x * 3 for x in range(6) if x % 2 == 0] is [0, 6, 12]. The expression can be a method: [m.upper() for m in orders] builds a list of every name in orders in capital letters. To choose one of two values, write if ... else in front of the for. An else at the back gives a SyntaxError. A comprehension in curly braces with key: value builds a dictionary.

⚡ Three lines become one

Write:

prices = [15, 5, 12]
raised = [p + 2 for p in prices]
print(raised)   # [17, 7, 14]
print(prices)   # [15, 5, 12]

Meaning: The second line is a list comprehension. Its shape is [expression for item in iterable]. With a for loop, the same work takes three lines. Read it from the middle: "for each p in prices, put in p + 2". So the expression is p + 2, and the iterable (what the for goes through) is prices. The result is a new list, and the original list doesn't change.

⚡ Filter with if

Guess first: what does [x * 3 for x in range(6) if x % 2 == 0] give?

[0, 6, 12]. range(6) is 0 to 5. Only the even numbers pass the if (x % 2 == 0): 0, 2 and 4. Then each of them is multiplied by 3.

Meaning: An if at the back filters. Items whose condition is False are skipped, and their expression isn't computed at all.

⚡ The expression can be a method

Write:

orders = ["coffee with milk", "sweet tea", "toast"]

print([m.upper() for m in orders])           # ['COFFEE WITH MILK', 'SWEET TEA', 'TOAST']

Meaning: m.upper() is called for each item, so every name is written in capital letters.

⚡ Choosing a value: if-else in front

Guess first: does [p for p in prices if p < 10 else 0] work?

No: SyntaxError: invalid syntax. The filter at the back has no else.

Meaning: Want every item to stay in, with its value chosen from two options? Put if ... else in front of the for: ["cheap" if p < 10 else "pricey" for p in prices]. A price under 10 gets the label cheap, the others pricey.

What you will learn