Skip to content
Visual explainer 2h to learn 4 steps

Comprehensions

Turn simple build-a-list loops into list, dict and set comprehensions.

By Invicly Tech, , in Python Programming from Zero. About 12 minutes to read.

Topic 11 of 34

In short

A comprehension builds a list, dict or set in a single readable expression: loop over a source, optionally filter, and transform each item. It replaces the common create-empty-then-append pattern.

Explained simply

A comprehension is a short way to build a new list, dict or set from another collection in one line. Instead of making an empty list, writing a loop and calling append, you describe the result you want, and Python builds it.

It reads left to right almost like a sentence. [price * 2 for price in prices if price > 10] means "price times two, for each price in prices, if the price is over 10". The part before for says what goes into the new list; the if at the end decides which items get in.

Curly braces with a colon build a dict, {name: len(name) for name in names}, and curly braces without a colon build a set, which drops duplicates. Round brackets give a generator expression, which produces values one at a time, perfect for feeding straight into sum(), max() or any().

Comprehensions are not always better. If each item needs several steps, error handling or printing, a normal loop is easier to read and to debug. The goal is always clear code, not the shortest code.

Press Play on a diagram to walk through it one step at a time.

Flow[x * x for x in nums if x > 0]
  1. Step 1
    for x in nums

    Take each item from the source

  2. Step 2
    if x > 0

    Optional filter: skip items that fail

  3. Step 3
    x * x

    Transform the item that passed

  4. Step 4
    Collect

    Add result to the new list, dict or set

FlowOrder of [(r, c) for r in range(2) for c in range(3)]
  1. 1
    r = 0

    Outer for clause, written first

  2. 2
    c = 0, 1, 2

    Inner clause runs fully: (0, 0) (0, 1) (0, 2)

  3. 3
    r = 1

    Outer clause moves on

  4. 4
    c = 0, 1, 2

    (1, 0) (1, 1) (1, 2)

  5. 5
    Done

    6 pairs, same order as nested loops

In depth

How a comprehension maps onto a loop

Every list comprehension has an exact loop equivalent. [EXPR for X in SOURCE if COND] does the same as: result = [], then for X in SOURCE:, then if COND:, then result.append(EXPR). The only reorder is that EXPR, which runs last, is written first.

More clauses follow the same rule. Several for clauses nest in the order you write them, outer first: [(x, y) for x in "ab" for y in "12"] gives ('a', '1'), ('a', '2'), ('b', '1'), ('b', '2'). Several if clauses must all be true.

A comprehension has its own scope, so its loop variable does not leak out and does not overwrite a variable with the same name outside. Python 3.12 made comprehensions faster by running them inline, but kept that isolation. For simple build-a-list work they are usually a little faster than a loop with append, though readability is the better reason to use them.

CompareThe same logic as a loop and as a comprehension
Loop
  • result = []
  • for n in nums:
  • if n % 2 == 0:
  • result.append(n * n)
Comprehension
  • [ ... ] creates the list
  • for n in nums
  • if n % 2 == 0
  • n * n, written first

Filter vs transform: where if and else go

There are two different ifs, and they live in different places. A trailing if filters: [x for x in nums if x > 0] drops items that fail, and it cannot have an else. A conditional expression at the front transforms: ["even" if n % 2 == 0 else "odd" for n in nums] keeps every item but changes what is stored, and it must have an else.

You can use both at once: [x if x > 0 else 0 for x in readings if x is not None] first drops missing readings, then turns negatives into 0. Writing [x for x in nums if x > 0 else 0] is a SyntaxError, which is the usual sign that the condition belongs at the front.

If the expression is expensive and you need its result in both the filter and the output, the walrus operator (Python 3.8+) avoids calling it twice: [y for x in data if (y := score(x)) > 50]. Use it sparingly; a loop is often clearer.

Dict and set comprehensions

A dict comprehension uses braces and a colon: {name: len(name) for name in names}. Two everyday uses are filtering a dict, {k: v for k, v in stock.items() if v > 0}, and transforming its values, {k: round(v, 2) for k, v in prices.items()}. If the same key is produced twice, the last value wins. For pairing two lists, dict(zip(keys, values)) is simpler than a comprehension.

A set comprehension uses braces without a colon, {w.lower() for w in words}, and naturally removes duplicates. That makes it ideal for questions like "which domains appear in this email list?".

There is no tuple comprehension. Round brackets make a generator expression instead, so write tuple(x for x in items) when you need a tuple.

MapThe comprehension family
Comprehensions
  • List [ ... ]
    • Keeps order and duplicates
    • [x * 2 for x in xs]
  • Dict { k: v ... }
    • Last duplicate key wins
    • {w: len(w) for w in ws}
  • Set { ... }
    • Unique items, no order
    • {w.lower() for w in ws}
  • Generator ( ... )
    • Lazy, one pass only
    • sum(x * x for x in xs)

Generator expressions and memory

A list comprehension builds the whole list in memory at once. A generator expression, written with round brackets, builds nothing up front: it produces one value each time it is asked. (x * x for x in range(1_000_000)) is an object of about 200 bytes, while the equivalent list needs over 8 MB just for its slots.

When you pass a generator straight into a function, the function's own parentheses are enough: sum(x * x for x in nums), max(len(w) for w in words), any(line.startswith("ERROR") for line in f). any() and all() even stop early once they know the answer.

The catch is that a generator is used up after one pass. Looping over it a second time gives nothing, and it has no len() or indexing. Use a list when you need to look at the results more than once, count them or pick items by position.

When a plain loop is clearer

Comprehensions are for building a collection from simple expressions. Switch to a normal for loop when any of these is true. Each item needs several statements, such as parsing, validating and converting. You need try/except around part of the work. You want side effects like print() or writing to a file; [print(x) for x in xs] builds a useless list of None values. You need break to stop early. Or the comprehension has more than two for clauses, or nested ifs that you cannot read aloud in one breath.

A good test: if it does not fit comfortably on one or two lines, or a teammate would need to stop and decode it, write the loop. Another good option is to move the per-item logic into a small named function, then use it in a short comprehension: [parse_row(r) for r in rows].

Learn it in 4 short steps

About 30m each. Track them with a timer in your plan.

  1. 1
    Write list comprehensions with conditions~30m
  2. 2
    Build dicts with dict comprehensions~30m
  3. 3
    Build sets with set comprehensions~30m
  4. 4
    Know when a plain loop is clearer~30m

Key points

  • List: [expr for item in source if condition].
  • Dict: {key: value for item in source}; set: {expr for item in source}.
  • The result is always a brand-new collection; the source is unchanged.
  • If it needs several statements or nested logic, a plain loop is clearer.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
nums = [3, -1, 4, -5, 9]

# loop version
squares = []
for x in nums:
    if x > 0:
        squares.append(x * x)

# comprehension version
squares = [x * x for x in nums if x > 0]   # [9, 16, 81]

names = ["ana", "bo", "cy"]
lengths = {n: len(n) for n in names}       # {'ana': 3, 'bo': 2, 'cy': 2}
first_letters = {n[0] for n in names}      # {'a', 'b', 'c'}
print(squares, lengths, first_letters)

Cleaning a messy list of emails

A sign-up form gave you emails with stray spaces, mixed case and blank entries. Step 1: a list comprehension strips and lower-cases each email, and its trailing if drops entries that are empty after stripping. Step 2: the same logic as a set comprehension removes duplicates, and sorted() gives a stable order. Step 3: a dict comprehension maps each email to its domain. Each step is one readable line.

python
raw = [" Ana@Mail.com", "bo@mail.com ", "", "ANA@mail.com", "  "]

cleaned = [e.strip().lower() for e in raw if e.strip()]
print(cleaned)   # ['ana@mail.com', 'bo@mail.com', 'ana@mail.com']

unique = sorted({e.strip().lower() for e in raw if e.strip()})
print(unique)    # ['ana@mail.com', 'bo@mail.com']

domains = {e: e.split("@")[1] for e in unique}
print(domains)   # {'ana@mail.com': 'mail.com', 'bo@mail.com': 'mail.com'}

Flattening and transposing a grid

grid is a list of rows. Step 1: two for clauses flatten it; read them as nested loops, rows first, then the numbers in each row. Step 2: a nested comprehension transposes it: the outer one walks column numbers, the inner one picks that column from every row. Step 3: a generator expression feeds sum() directly, with a filter, and no temporary list is built.

python
grid = [[1, 2, 3],
        [4, 5, 6]]

flat = [n for row in grid for n in row]
print(flat)            # [1, 2, 3, 4, 5, 6]

transposed = [[row[i] for row in grid] for i in range(3)]
print(transposed)      # [[1, 4], [2, 5], [3, 6]]

print(sum(n for n in flat if n % 2 == 0))   # 12

Quick reference

  • [f(x) for x in xs if test(x)]: the trailing if filters items out
  • [a if cond else b for x in xs]: if/else at the front transforms every item
  • {k: v for k, v in d.items() if v} keeps only entries with truthy values
  • {v: k for k, v in d.items()} inverts a dict; duplicate values keep only the last key
  • [n for row in grid for n in row] flattens: for clauses read like nested loops
  • sum(x * x for x in nums) uses a generator, so no temporary list is built
  • A generator can be looped over only once; build a list if you need it twice
  • Never use a comprehension just for side effects like print(); write a for loop

Common mistakes

  • Cramming nested loops and conditions into one unreadable line.
  • Using a comprehension only for side effects like print(); use a loop.
  • Putting if/else in the wrong place: [a if c else b for x in xs] transforms, it does not filter.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What is [x * 2 for x in range(5) if x % 2]?

Question 2

2Which of these is a SyntaxError?

Question 3

3What kind of object does (n * n for n in nums) create?

Question 4

4What is {w[0]: w for w in ["apple", "avocado", "banana"]}?

Question 5

5In [(x, y) for x in "ab" for y in "12"], which pair comes second?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    From temps_c = [12, 25, 31, 18, 40], build a list of the same temperatures in Fahrenheit (F = C * 9 / 5 + 32) and a list of only the Celsius values above 20.

  2. Exercise 2medium

    From words = ["Apple", "bob", "kayak", "Level", "python"], build a dict that maps each palindrome, in lower case, to its length, and a set of the lower-case first letters of all words.

  3. Exercise 3hard

    Parse lines = ["# config", "port=8080", "", "host=localhost", "debug=0"] into a dict, skipping blank lines and comments and turning digit-only values into ints. Decide whether a comprehension or a loop is clearer, and justify it.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Are list comprehensions faster than for loops?
Usually a little faster for simple build-a-list work, because the appending happens inside the interpreter. The main reason to use them is readability, not speed.
Is there a tuple comprehension in Python?
No. Round brackets make a generator expression. Use tuple(x for x in items) to build a tuple.
Can I use else in a list comprehension?
Only in the expression at the front: [a if cond else b for x in xs]. The filtering if at the end cannot have an else.
Does a comprehension's loop variable leak out?
No. In Python 3 a comprehension has its own scope, so its loop variable never overwrites a variable with the same name outside it.

Go deeper

ShareXLinkedInWhatsApp