Sub topic 9
Set comprehensions
A set comprehension builds a new set from an expression, a loop, and an optional filter, all in one line. This chapter covers the syntax, how it relates to list and dict comprehensions, and the errors people hit most often.
Prerequisites
This chapter assumes you know the following:
- Basic Python syntax,
forloops, and theinoperator. - List comprehensions, at least in outline.
- That set elements must be hashable and that sets drop duplicates (covered in earlier chapters).
The basic form
A set comprehension looks like a list comprehension, but it uses curly braces:
squares = {n * n for n in range(-3, 4)}
print(sorted(squares)) # [0, 1, 4, 9]The input range holds seven numbers: -3, -2, -1, 0, 1, 2, 3. Squaring them gives 9, 4, 1, 0, 1, 4, 9. The set keeps one copy of each value, so the result has four elements. A list comprehension over the same input would return seven.
The general shape is:
{expression for item in iterable}
{expression for item in iterable if condition}Python evaluates the expression once for each item that passes the condition. It adds each result to the set. If a value is already in the set, the add does nothing.
The result is a normal set. You can modify it, combine it with other sets, and use every method you have already seen.
words = ["Apple", "banana", "apple", "Cherry", "BANANA"]
normalized = {w.lower() for w in words}
print(sorted(normalized)) # ['apple', 'banana', 'cherry']
print(len(words), len(normalized)) # 5 3Here the comprehension does two jobs. It normalizes case, and it removes the duplicates that normalization reveals. This is the most common reason to reach for one.
Comparing the comprehension forms
Python has four comprehension forms. Only the brackets and the shape of the expression change.
| Form | Syntax | Result | Duplicates |
|---|---|---|---|
| List | `[x for x in data]` | `list` | Kept |
| Set | `{x for x in data}` | `set` | Removed |
| Dict | `{k: v for k, v in pairs}` | `dict` | Later key replaces earlier |
| Generator | `(x for x in data)` | generator | Kept, produced lazily |
Set and dict comprehensions both use braces. Python tells them apart by looking at the expression. A bare expression makes a set. A key: value pair makes a dict.
Filtering with a condition
An if clause at the end skips items. Only items that pass the test reach the expression.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_squares = {n * n for n in numbers if n % 2 == 0}
print(sorted(even_squares)) # [4, 16, 36, 64, 100]You can also apply a condition inside the expression with a conditional expression. This does not skip items. It chooses between two values:
labels = {"even" if n % 2 == 0 else "odd" for n in numbers}
print(sorted(labels)) # ['even', 'odd']Position matters. A trailing if filters. An if ... else must come before the for, as part of the expression. Writing {n for n in numbers if n > 5 else 0} is a SyntaxError.
Multiple loops and conditions
A comprehension can contain several for clauses and several if clauses. They read in the same order you would write nested loops.
pairs = {(a, b) for a in range(3) for b in range(3) if a < b}
print(sorted(pairs)) # [(0, 1), (0, 2), (1, 2)]This is equivalent to:
pairs = set()
for a in range(3):
for b in range(3):
if a < b:
pairs.add((a, b))The elements here are tuples, which are hashable. A list as the expression would fail, as the next section explains.
A common use is flattening nested data into a set of unique values:
orders = [
{"id": 1, "tags": ["rush", "gift"]},
{"id": 2, "tags": ["gift"]},
{"id": 3, "tags": ["bulk", "rush"]},
]
all_tags = {tag for order in orders for tag in order["tags"]}
print(sorted(all_tags)) # ['bulk', 'gift', 'rush']Read the loops left to right: first loop over orders, then loop over each order's tags.
The expression must be hashable
The expression result becomes a set element, so it must be hashable. If it is not, Python raises a TypeError as soon as it tries to add the value.
try:
bad = {[n, n + 1] for n in range(3)}
except TypeError as e:
print(e) # unhashable type: 'list'
good = {(n, n + 1) for n in range(3)}
print(sorted(good)) # [(0, 1), (1, 2), (2, 3)]The fix is to use an immutable equivalent. Use a tuple instead of a list. Use a frozenset instead of a set.
groups = [[1, 2], [2, 1], [3]]
unique_groups = {frozenset(g) for g in groups}
print(len(unique_groups)) # 2The first two groups hold the same elements, so their frozensets are equal and collapse into one. This pattern is useful when order inside each group should not matter.
Scope and the loop variable
A comprehension runs in its own scope. The loop variable does not leak into the surrounding code.
x = "outer"
result = {x for x in range(3)}
print(x) # outerThe x inside the comprehension is separate from the x outside. In Python 2, list comprehensions leaked their variable. In Python 3, no comprehension does.
Order is not guaranteed
A set comprehension produces an unordered result. Do not depend on the order in which elements appear when you print or iterate it. If you need stable output, wrap the set in sorted(), as the examples above do.
If you need to remove duplicates and keep the first-seen order, a set comprehension is the wrong tool. Use dict.fromkeys:
items = ["b", "a", "b", "c", "a"]
print(list(dict.fromkeys(items))) # ['b', 'a', 'c']Set comprehension versus set(generator)
These two lines build the same set:
a = {n % 5 for n in range(20)}
b = set(n % 5 for n in range(20))
print(a == b) # TrueThe comprehension is slightly shorter and usually a little faster, because it avoids the extra call through the generator machinery. The set(...) form is useful when you already have a generator expression, or when you want to pass any iterable straight through:
unique_chars = set("mississippi")
print(sorted(unique_chars)) # ['i', 'm', 'p', 's']When you are not transforming or filtering anything, set(iterable) is clearer than {x for x in iterable}.
Common errors
The mistakes below come up often.
- Expecting
{}to make an empty set. An empty comprehension result is still a set, but a literal{}is a dict. Useset()for an empty set. - Using a mutable expression.
{[a, b] for ...}and{{...} for ...}raiseTypeError. Convert to a tuple or frozenset. - Putting
elseafter a filter. A trailingifcannot have anelse. Move the conditional expression into the expression part. - Expecting order or length to match the input. The set may be much shorter than the input, and its iteration order is not the input order.
- Confusing set and dict forms.
{k: v for ...}is a dict.{k for ...}is a set. A missing colon changes the type. - Using a comprehension for side effects. Writing
{print(x) for x in data}builds a throwaway set ofNone. Use aforloop instead.
The last one is worth a short demonstration:
data = [1, 2, 3]
result = {print(x) for x in data}
print(result) # {None}The comprehension prints 1, 2 and 3, then returns a set holding one None, because every print call returns None. The side effect worked, but the result is useless, and a reader will wonder why you built it.
How the pieces fit together
Each pass through the loop either skips the item, raises an error, or adds a value. The set silently ignores a value it already holds.
A worked example: finding shared users
Set comprehensions combine well with the set operators from earlier chapters. This example finds which users were active on both days:
monday = [
{"user": "ana", "action": "login"},
{"user": "ben", "action": "login"},
{"user": "ana", "action": "purchase"},
]
tuesday = [
{"user": "ben", "action": "login"},
{"user": "cy", "action": "login"},
{"user": "ben", "action": "purchase"},
]
monday_users = {e["user"] for e in monday}
tuesday_users = {e["user"] for e in tuesday}
print(sorted(monday_users & tuesday_users)) # ['ben']
print(sorted(monday_users | tuesday_users)) # ['ana', 'ben', 'cy']
print(sorted(monday_users - tuesday_users)) # ['ana']Each comprehension reduces a list of events to a set of unique users. The operators then answer the questions. The & result is users on both days, | is everyone, and - is users seen only on Monday.
Summary
{expr for x in it}builds a set, and a trailingiffilters items.- The expression must produce hashable values.
- The result has no guaranteed order and is often shorter than the input.
- Use
set(iterable)when you are not transforming anything, anddict.fromkeyswhen order must be kept. - Use a plain loop for side effects or logic that gets hard to read.
Exercise
Given words = ["Tea", "tea", "Coffee", "cocoa", "COCOA", "milk"], write a set comprehension that returns the lowercase versions of only the words longer than 3 characters. What does the set contain, and why is it smaller than the list?
Show answer
{w.lower() for w in words if len(w) > 3} gives {"coffee", "cocoa", "milk"}. "Tea" and "tea" are filtered out by the length test. "cocoa" and "COCOA" both become "cocoa", so the set keeps one copy. The set is smaller because the filter removes short words and the set removes duplicates.
Exercise
What happens when you run {[x, x * 2] for x in range(3)}, and how do you fix it so each pair stays together?
Show answer
It raises TypeError: unhashable type: 'list', because lists are mutable and cannot be set elements. Use tuples instead: {(x, x * 2) for x in range(3)} gives {(0, 0), (1, 2), (2, 4)}.