Tutorials / Python: Intermediate to Advanced / List, dict and set comprehensions

List, dict and set comprehensions

13 min read python
Course contents (15 lessons)
  1. Iteration the Python way
  2. List, dict and set comprehensions
  3. Iterators and generators
  4. Functions as building blocks
  5. Closures and decorators
  6. Context managers and the with statement
  7. Object-oriented Python in depth
  8. Classes and dataclasses
  9. Properties and special (dunder) methods
  10. Inheritance versus composition
  11. Quality: types, packaging and tests
  12. Type hints and mypy
  13. Packaging a project with pyproject.toml
  14. Testing with pytest
  15. Async code and web APIs
  16. async and await with asyncio
  17. Working with HTTP APIs and JSON
  18. Performance, concurrency and a final project
  19. Performance and profiling
  20. Concurrency: threads versus processes
  21. Final project: a price tracker command-line tool

A loop in one expression

A huge share of loops do one of two jobs: transform each item, or filter items. Python gives these jobs their own syntax, the comprehension. Here is the long way to get the net price of each order line:

lines = [("pen", 40, 12), ("notebook", 150, 5), ("stapler", 480, 1)]

totals = []
for name, price, qty in lines:
    totals.append(price * qty)

And here is the comprehension:

lines = [("pen", 40, 12), ("notebook", 150, 5), ("stapler", 480, 1), ("tape", 35, 0)]

# list comprehension: transform
totals = [price * qty for name, price, qty in lines]

# with a filter: only lines that were actually ordered
ordered = [name for name, price, qty in lines if qty > 0]

# dict comprehension: name -> line total
total_by_name = {name: price * qty for name, price, qty in lines}

# set comprehension: unique first letters
initials = {name[0] for name, *_ in lines}

# conditional expression inside: label each line
labels = ["bulk" if qty >= 10 else "small" for _, _, qty in lines]

print(totals)
print(ordered)
print(total_by_name)
print(sorted(initials))
print(labels)

Output:

[480, 750, 480, 0]
['pen', 'notebook', 'stapler']
{'pen': 480, 'notebook': 750, 'stapler': 480, 'tape': 0}
['n', 'p', 's', 't']
['bulk', 'small', 'small', 'small']

The shape of a comprehension

Read a comprehension in this order: the expression at the front is what you produce, the for part says where items come from, and an optional if at the end filters. Square brackets make a list, curly braces with key: value make a dictionary, and curly braces with a single expression make a set.

Notice the two different uses of if. At the end it filters: items failing the test are dropped. At the front, as part of a if cond else b, it chooses a value, and every item stays. Mixing these up is the most common comprehension mistake. A filter has no else. A choice always has one.

Nested loops

You can use more than one for. The order matches the order of nested loops written out:

sizes = ["S", "M"]
colours = ["red", "blue"]
variants = [f"{c}-{s}" for c in colours for s in sizes]
print(variants)    # ['red-S', 'red-M', 'blue-S', 'blue-M']

Flattening a list of lists is a typical use: flat = [x for row in rows for x in row]. It reads like the loops in the same order, outer first.

Generator expressions

Use round brackets instead of square ones and you get a generator expression. It does not build the list. It produces values one at a time as they are asked for.

total = sum(price * qty for _, price, qty in lines)
has_free = any(price == 0 for _, price, _ in lines)

When the comprehension is the only argument of a function call, the extra brackets are optional. If you only need to feed the values into sum, max, any or all, a generator expression saves memory, because no intermediate list exists. We look at generators fully in the next lesson.

A note on speed

A comprehension is usually a bit faster than the equivalent loop with append, because the repeated method lookup is avoided. But the real benefit is readability. Do not choose it for speed alone.

When not to use one

Comprehensions should be easy to read at a glance. I follow a simple rule: if it does not fit on one or two lines, or needs more than one condition and a nested loop, use a normal loop.

# Hard to read. Please do not write this.
result = [transform(x) for group in data for x in group if x.active and x.score > 10 if not x.hidden]

Another warning: do not use a comprehension only for side effects, such as [print(x) for x in items]. It builds a throwaway list of None values and confuses the reader. Use a for loop.

Scope

The loop variable of a comprehension lives inside it and does not leak out into the surrounding code. In Python 2 it did. In Python 3 the name is local to the comprehension, which avoids a whole class of accidental overwrites.

The walrus operator

Sometimes you want to call an expensive function once and use the result both in the filter and in the output. The assignment expression := allows this:

raw = ["12", "x", "7", ""]
numbers = [n for s in raw if (n := to_int(s)) is not None]

Here to_int would be your own function that returns None for bad input. Use this sparingly. It is a handy tool, but too many of them make code harder to read.

Try it yourself

Given the list words = ["apple", "Banana", "cherry", "date", "Elderberry", "fig"], use comprehensions to build: (1) a list of the lengths of all words, (2) a list of words longer than four characters in lowercase, (3) a dictionary mapping each word to its length, (4) a set of the first letters in uppercase. Then rewrite (2) as a normal loop and decide which version you find easier to read.

python
lines = [("pen", 40, 12), ("notebook", 150, 5), ("stapler", 480, 1), ("tape", 35, 0)]

# list comprehension: transform
totals = [price * qty for name, price, qty in lines]

# with a filter: only lines that were actually ordered
ordered = [name for name, price, qty in lines if qty > 0]

# dict comprehension: name -> line total
total_by_name = {name: price * qty for name, price, qty in lines}

# set comprehension: unique first letters
initials = {name[0] for name, *_ in lines}

# conditional expression inside: label each line
labels = ["bulk" if qty >= 10 else "small" for _, _, qty in lines]

print(totals)
print(ordered)
print(total_by_name)
print(sorted(initials))
print(labels)

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account