List, Dict and Set Comprehensions
Build a whole collection in one clear, readable line
- write list, dict and set comprehensions fluently,
- add filtering with a trailing
ifand choose values with a conditional expression, - nest loops inside a single comprehension,
- use a set comprehension to deduplicate, and a dict comprehension to remap keys and values,
- decide honestly when a comprehension helps and when a plain loop or a generator is the better call.
1. From loop to comprehension
You already know how to build a list with a loop: start empty, iterate, and append. Suppose you want the squares of the numbers 0 through 4.
squares = []
for n in range(5):
squares.append(n * n)
print(squares)
Output:
[0, 1, 4, 9, 16]
A list comprehension expresses the exact same intent in one line. The three moving parts of the loop — the output expression, the loop variable, and the iterable — line up left to right:
squares = [n * n for n in range(5)]
print(squares) # [0, 1, 4, 9, 16]
Think of it as an assembly line: items enter from the iterable on the right, each one is transformed by the expression on the left, and the finished parts collect into a brand-new list. Nothing is mutated in place; the comprehension always produces a fresh collection.
2. Anatomy of a comprehension
Every comprehension has the same skeleton. Reading it aloud helps: "the expression, for each item in the iterable, if the condition holds." The if clause is optional.
Although you write the expression first, Python runs the for clause first to produce items, applies the if filter, and only then evaluates the expression for each survivor. Keeping that order in mind explains every result you will see.