Advanced   Chapter 146 · 30 min read · Module 11: Advanced Python

Comprehensions Advanced

Learning objectives
  • After this chapter you can write comprehensions with several for and if clauses.
  • You can tell a filter apart from a conditional expression inside a comprehension.
  • You can flatten and transpose nested lists using comprehensions.
  • You can build dictionaries and sets with comprehensions.
  • You can choose between a list comprehension and a generator expression.

You already know the basic list comprehension: a short way to build a list from a loop. In this chapter we go further. You will see how to use several for clauses, how to put conditions in two different places, how to build dictionaries and sets, and how to use generator expressions when you do not need a full list in memory.

Advanced does not mean complicated. The same simple pattern is used every time: an expression, then one or more for parts, then optional if parts. Once you can read this pattern from left to right, even long comprehensions become easy to follow. We will also talk about when a plain loop is the better choice, because readable code matters more than short code.

By the end of the chapter you will be able to flatten nested lists, transpose a matrix, group and invert data with dictionary comprehensions, and use the walrus operator inside a comprehension to avoid repeating work.

The full shape of a comprehension

A comprehension has three parts. First comes the output expression, which says what each item looks like. Then come one or more for clauses that say where the values come from. At the end you may add one or more if clauses that filter values out. For example [x * x for x in nums if x % 2 == 0] reads as: give me x * x for every x in nums where x is even.

There are four kinds. A list comprehension uses square brackets, a set comprehension uses curly braces with one expression, a dictionary comprehension uses curly braces with key: value, and a generator expression uses round brackets. The first three build a whole collection at once. The generator expression builds nothing up front and produces values one at a time when you ask for them.

Example 1: filter with if
nums = [1, 2, 3, 4, 5, 6, 7, 8]
squares = [n * n for n in nums if n % 2 == 0]
print(squares)
[4, 16, 36, 64]

Two places for a condition

A very common confusion is where to put the if. When if comes at the end, it filters: items that fail the test are dropped. When you want to keep every item but change its value, you need a conditional expression, A if test else B, and it goes at the front, as part of the output expression. A filter never has an else, while a conditional expression always needs one.

Example 2: filter versus conditional expression
nums = [3, -1, 4, -5, 9]
filtered = [n for n in nums if n > 0]
clipped = [n if n > 0 else 0 for n in nums]
print(filtered)
print(clipped)
[3, 4, 9] [3, 0, 4, 0, 9]
Rule of thumb: if at the end removes items, if ... else at the front changes items.

Nested loops and flattening

You can write more than one for clause. They run in the same order as nested loops written on separate lines: the first for is the outer loop and the next one is the inner loop. This makes flattening a list of lists very short. Read [x for row in grid for x in row] as: for each row in the grid, for each x in that row, give x. Beginners often write the clauses in the opposite order, which raises a NameError because row is not defined yet.

Example 3: flatten and combine
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [x for row in grid for x in row]
print(flat)
pairs = [(a, b) for a in 'ab' for b in (1, 2)]
print(pairs)
transposed = [[row[i] for row in grid] for i in range(3)]
print(transposed)
[1, 2, 3, 4, 5, 6, 7, 8, 9] [('a', 1), ('a', 2), ('b', 1), ('b', 2)] [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

The last line of that example shows a comprehension inside a comprehension. The inner one builds one new row by taking column i from every old row, and the outer one repeats this for each column. This is a nested comprehension, which is different from two for clauses in one comprehension. Nested comprehensions create lists of lists, while multiple for clauses create one flat list.

Dictionary and set comprehensions

A dictionary comprehension builds key and value pairs in one line. It is perfect for inverting a mapping, counting lengths, or filtering a dictionary. A set comprehension works the same way but keeps only unique values. Remember that {} alone is an empty dictionary, not an empty set, so use set() when you need an empty set.

Example 4: dict and set comprehensions
words = ['apple', 'kiwi', 'banana', 'fig']
lengths = {w: len(w) for w in words}
print(lengths)
swapped = {v: k for k, v in lengths.items()}
print(swapped)
first_letters = {w[0] for w in words}
print(sorted(first_letters))
long_ones = {w: n for w, n in lengths.items() if n > 4}
print(long_ones)
{'apple': 5, 'kiwi': 4, 'banana': 6, 'fig': 3} {5: 'apple', 4: 'kiwi', 6: 'banana', 3: 'fig'} ['a', 'b', 'f', 'k'] {'apple': 5, 'banana': 6}

Generator expressions

If you only need to loop over the results once, or pass them to a function like sum, max or any, you do not need to store a list. A generator expression looks like a list comprehension with round brackets. It uses almost no memory because it creates each value only when it is needed. When a generator expression is the only argument of a function call you can drop the extra brackets: sum(x * x for x in range(5)). A generator can be used only once; after it is exhausted it gives nothing more.

Example 5: generator expression
total = sum(x * x for x in range(1, 6))
print(total)
gen = (x * 2 for x in range(3))
print(next(gen))
print(list(gen))
print(list(gen))
55 0 [2, 4] []

The walrus operator in comprehensions

Sometimes you need the result of a calculation both in the filter and in the output. Calling the function twice wastes time. Python 3.8 added the assignment expression :=, called the walrus operator, which lets you name a value inside an expression. In a comprehension, put the walrus in the if clause and use the name in the output expression. The name is also available after the comprehension finishes, because it is bound in the surrounding scope.

Example 6: walrus in a comprehension
def slow_square(n):
    return n * n

values = [r for n in range(6) if (r := slow_square(n)) > 5]
print(values)
[9, 16, 25]

Scope and readability

The loop variable of a comprehension lives in its own small scope. In Python 3 it does not leak out, so a name you used earlier is not changed. This protects you from a bug that was common in Python 2. Still, a comprehension should stay easy to read. If you need more than two for clauses, or a long condition, or side effects such as printing, switch to a normal loop. Short and clear beats clever.

Example 7: reading input with a comprehension
numbers = [int(t) for t in input().split()]
print(sum(numbers))
print([n for n in numbers if n % 2])
30 [7, 9]

Python syntax

Syntax
[expression for item in iterable if condition]
Syntax
[a if test else b for item in iterable]
Syntax
[expr for outer in outer_iter for inner in outer]
Syntax
{key: value for key, value in pairs}
Syntax
{expression for item in iterable}
Syntax
(expression for item in iterable)

Real-world applications

  • Flattening lists of lists that come from files or APIs.
  • Cleaning data by converting types and dropping bad values.
  • Building lookup dictionaries from lists of records.
  • Summing or counting large data without creating big lists.
  • Transposing tables and matrices.

Common mistakes

Mistake: Writing [x for x in data else 0] or putting else in a filter.
Fix: A filter at the end has no else. Use [x if cond else 0 for x in data] with the conditional expression at the front.
Mistake: Reversing the order of nested for clauses when flattening.
Fix: Write the clauses in the same order as nested loops: outer first, then inner.
Mistake: Using {} to create an empty set.
Fix: {} is an empty dictionary. Use set() for an empty set.
Mistake: Looping over the same generator twice and getting nothing the second time.
Fix: A generator is used up after one pass. Create it again or use a list if you need several passes.
Mistake: Packing too much logic into one long comprehension.
Fix: If it does not fit comfortably on one or two lines, use a regular loop.

Important tips

  • Read a comprehension aloud from the left: what is built, from where, under which condition.
  • Use a generator expression inside sum, max, min, any and all.
  • Give the loop variable a meaningful name instead of always using x.
  • Use the walrus operator only when it saves a repeated calculation.

Key points summary

  • A comprehension is an expression, so it can be used anywhere a value is allowed.
  • The final if filters; the front if-else transforms.
  • Several for clauses run like nested loops, outer first.
  • Dict and set comprehensions use curly braces.
  • Generator expressions use round brackets and are lazy.
  • The loop variable does not leak out of a comprehension.

Exam and interview points

  • Know where if and if-else go in a comprehension.
  • Predict the output of nested comprehensions step by step.
  • Remember that {} is a dict and set() is an empty set.
  • A generator expression is exhausted after one iteration.
  • Walrus operator needs Python 3.8 or newer.

Quick revision

  • [expr for x in it if cond] filters.
  • [a if c else b for x in it] transforms.
  • Multiple for clauses: outer first.
  • {k: v for ...} makes dicts; {e for ...} makes sets.
  • (e for ...) is a lazy generator.
  • Use := to reuse a computed value.

Frequently asked questions

Are comprehensions faster than loops?

Usually a little faster than building a list with append in a loop, but the main benefit is clear, short code. Do not use them only for speed.

Can I use break or continue in a comprehension?

No. Use an if clause to skip items, and use a normal loop or itertools.takewhile if you need to stop early.

When should I use a generator expression instead of a list?

When you only loop once or pass the values to a function like sum. It saves memory because values are produced on demand.

Can a comprehension have side effects such as print?

It can, but it is bad style. A comprehension should build a value. Use a for loop for actions.

Practise this chapter

19 practice questions Take the chapter quiz

Related chapters