Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

Advanced Python & Software Engineering — Alpha School

Lesson 6: Comprehensions — Lists, Dicts and Sets Done Well

A comprehension is Python's compact way of building a collection from another collection. Instead of creating an empty list, looping over some data, and appending each transformed item, you write the whole operation in a single readable line: [x * x for x in range(5)]. The shape is always the same — an expression, then a for clause, then an optional if clause — and once you learn to read that shape, comprehensions become the clearest way to express a transformation in Python.

The same pattern works for dictionaries and sets. A dict comprehension builds key-value pairs, which is handy for turning a list of names into a lookup table or for flipping a mapping around. A set comprehension builds a set, automatically dropping duplicates. The example below shows all three at once: squares as a list, name lengths as a dictionary, and the set of first letters of a group of words. Notice how each one reads almost like an English sentence — that is the point.

squares = [x * x for x in range(5)]
print(squares)  # [0, 1, 4, 9, 16]

names = ["ana", "ben", "cy"]
lengths = {name: len(name) for name in names}
print(lengths)  # {'ana': 3, 'ben': 3, 'cy': 2}

words = ["apple", "apricot", "banana", "berry"]
initials = {w[0] for w in words}
print(initials)  # {'a', 'b'} — duplicates removed

evens = [x for x in range(10) if x % 2 == 0]
print(evens)  # [0, 2, 4, 6, 8]

When a comprehension goes too far

Comprehensions have a dark side: they tempt you to squeeze too much into one line. A comprehension with two nested loops and a condition is hard to read, and a hard-to-read line is a bug waiting to happen. A good rule is that a comprehension should express one transformation or one filter. If you need two loops, or a condition that itself needs explaining, write a normal loop instead — or break the work into two comprehensions with a clear name for the intermediate result. Readability is not a luxury in Python; it is the whole point of the language.

There is also a performance point worth knowing. A comprehension is usually faster than an equivalent loop with append, because the work happens inside the interpreter's optimised machinery rather than through repeated method calls. The difference is small for short lists and large for long ones, but speed is rarely the reason to choose a comprehension — clarity is. Choose the comprehension when it makes the intent obvious at a glance, and choose the loop the moment the comprehension starts to feel clever.

Going further

A comprehension can also choose between two values for each item, using a conditional expression: [x if x >= 0 else 0 for x in readings] replaces every negative reading with zero. Notice the difference from the filter clause: the if at the end of a comprehension decides whether an item is included at all, while the if ... else ... before the for decides which value to produce for each item. Mixing the two up is a common mistake, and reading the comprehension aloud usually reveals which one you meant.

Dict comprehensions have a handy trick of their own: inverting a mapping. If you have a dictionary of names to ages, {age: name for name, age in ages.items()} builds the reverse lookup — but only if the values are unique. When two names share an age, the later one overwrites the earlier one, and data is silently lost. That is not a reason to avoid the pattern; it is a reason to check the assumption first. A comprehension is a sharp tool, and like any sharp tool it rewards knowing exactly what it does with duplicates, missing keys, and unexpected values.

A good way to practise comprehensions is to rewrite a piece of your own code that builds a list with a loop and an append, and compare the two versions side by side. Ask yourself three questions: is the comprehension shorter, is it clearer, and would a teammate understand it at a glance? If the answer to all three is yes, keep the comprehension. If the answer to the third is no, keep the loop — readability is judged by the reader, not the writer. Over a week of doing this, you will develop a reliable instinct for the boundary, which is far more valuable than any rule about when comprehensions are allowed.

Key Terms

Comprehension
A compact expression that builds a list, dict or set from an iterable in a single line.
List comprehension
A comprehension in square brackets that builds a list, such as [x * x for x in range(5)].
Dict comprehension
A comprehension in braces with key: value pairs, such as {name: len(name) for name in names}.
Set comprehension
A comprehension in braces with single values that builds a set, dropping duplicates.
Filter clause
The optional if part of a comprehension, which keeps only items that pass the test.
Nested comprehension
A comprehension containing another loop; readable for simple cases, confusing when overused.
Generator expression
A comprehension in round brackets that produces items lazily instead of building a list (see Lesson 7).

Discussion Questions

  1. Rewrite a loop you have written recently as a comprehension. Is the result clearer or harder to read — and why?
  2. When would you deliberately choose a plain for loop over a comprehension, even though the comprehension is shorter?
  3. Why does a set comprehension drop duplicates automatically, and when could that surprise you?

Practice Questions

  1. Write a list comprehension that produces the cubes of 1 to 5.
  2. Write a dict comprehension mapping each word in ["red", "blue"] to its length.
  3. What does {c for c in "banana"} produce?
  4. Add a filter to keep only the odd numbers from range(10) in a comprehension.
  5. Give one sign that a comprehension has become too complicated.
Show answers
  1. [x ** 3 for x in range(1, 6)] — [1, 8, 27, 64, 125]. The expression x ** 3 is evaluated for each x in the range.
  2. {w: len(w) for w in ["red", "blue"]} — {'red': 3, 'blue': 4}. The key is w and the value is len(w), built for each word.
  3. {'b', 'a', 'n'}. It is a set comprehension, so repeated letters appear only once.
  4. [x for x in range(10) if x % 2 == 1]. The if clause runs for each x and keeps only the ones that pass.
  5. Any one of: two nested loops, a long condition, or needing to re-read it to understand it. At that point a plain loop, or splitting the work into named steps, is clearer.
Keep reading to complete this lesson