Kodokon kodokon.com

List and dictionary comprehensions

Replace your building loops with expressive comprehensions, to transform, filter and reindex your data.

8 min · 3 questions

Open this lesson in Kodokon

A list comprehension condenses the most common pattern in programming: building a list by transforming or filtering a sequence. The syntax reads like a sentence: [expression for element in sequence if condition]. Same result as a loop with append, in a single declarative line that every Python developer recognizes instantly.

PYTHON
prices = [12.0, 49.9, 5.5, 199.0]

with_tax = [round(p * 1.2, 2) for p in prices]
cheap = [p for p in prices if p < 50]

print(with_tax)  # [14.4, 59.88, 6.6, 238.8]
print(cheap)     # [12.0, 49.9, 5.5]
Transform with the expression, filter with the trailing if.

The dictionary comprehension follows the same logic with the {key: value for ...} syntax. A very common use case in projects: reindexing a list of objects by their identifier, to then get instant lookups instead of scanning the list every time you need something.

PYTHON
users = [
    {"id": 7, "name": "Alice"},
    {"id": 12, "name": "Bruno"},
    {"id": 31, "name": "Chloe"},
]

by_id = {u["id"]: u["name"] for u in users}
print(by_id[12])    # Bruno
print(31 in by_id)  # True
Reindexing by identifier: a classic of professional code.

Two positions for if, two different roles. Placed after the for, it filters: rejected elements don't appear in the result. Placed before the for, as a conditional expression (a if condition else b), it chooses a value for each element: the list then keeps the same length as the source.

PYTHON
scores = [45, 82, 67, 91]

labels = ["pass" if s >= 60 else "fail" for s in scores]
print(labels)  # ['fail', 'pass', 'pass', 'pass']
The conditional expression transforms each element without removing any.

Knowledge check

Make sure you remember the key points of this lesson.

  1. In [x * 2 for x in data if x > 0], what is the role of the if?
    • It chooses between two values for each element
    • It filters: only positive elements are kept
    • It stops the comprehension at the first negative element
  2. What does {n: n * n for n in range(3)} produce?
    • {0: 0, 1: 1, 2: 4}
    • {1: 1, 2: 4, 3: 9}
    • [0, 1, 4]
    • {0, 1, 4}
  3. When is it better to replace a comprehension with a classic loop?
    • When the logic becomes complex or nested
    • As soon as the list exceeds a hundred elements
    • Never, the comprehension is always preferable