Sub topic 6
Building sets with set comprehensions
This chapter assumes you know Python for loops and range, the built-in list, dict, and set types, basic comparisons, and how to call append. It also assumes you have seen list comprehensions and the trailing if filter from earlier chapters.
What a set comprehension is
A set comprehension builds a set from any iterable. It uses the same for and if clauses as a list comprehension, but it is wrapped in curly braces and has a single output expression.
words = ["apple", "banana", "cherry"]
unique_lengths = {len(w) for w in words}
print(unique_lengths) # {5, 6}The loop version does the same work. It creates an empty set, then calls add once per item.
words = ["apple", "banana", "cherry"]
unique_lengths = set()
for w in words:
unique_lengths.add(len(w))
print(unique_lengths) # {5, 6}"banana" and "cherry" both have length 6, but the result holds 6 only once. A set stores each value at most once, so the comprehension removes duplicates without any extra code.
The working model
A set comprehension evaluates in three steps:
- Python takes each item from the iterable, in order.
- If there is an
ifclause, it drops items for which the condition is false. - It evaluates the output expression for each remaining item and adds the result to the set.
Adding a value that is already in the set changes nothing. The comprehension therefore never fails on duplicates, and it does not tell you that any were found.
Filtering and transforming
Add a trailing if to keep only some items. This example collects the distinct first letters of the words that are longer than three characters, in lowercase.
names = ["Ada", "alan", "Grace", "grace", "Linus", "Li"]
initials = {name[0].lower() for name in names if len(name) > 3}
print(sorted(initials)) # ['a', 'g', 'l']Normalizing values in the output expression, as lower() does here, is a common use. "Grace" and "grace" collapse into one entry because their first letters match after normalization.
Set order is not guaranteed
A set has no reliable order. The printed form of a set with several items can differ between runs, especially for strings, because Python randomizes string hashing for each process. The earlier example prints {5, 6} for small integers, but do not rely on that. When you need stable output, for example in tests or logs, wrap the set in sorted(), as the example above does.
The empty set pitfall
Curly braces with nothing inside create an empty dict, not an empty set. To make an empty set, call set().
empty = set() # {} would create an empty dict, not an empty set
print(type({}), type(empty)) # <class 'dict'> <class 'set'>A comprehension is not affected by this problem. {x for x in []} is a valid set comprehension that produces an empty set, because the for clause tells Python it is a set. The trouble appears only when you write a literal and start with no items.
Set comprehension or list comprehension
Choose a set comprehension when you want uniqueness or fast membership tests later. Choose a list comprehension when order or duplicates matter. A common pattern is to build a set once and test against it many times.
allowed = {w.lower() for w in ["Red", "GREEN", "red", "Blue"]}
for color in ["red", "yellow", "blue"]:
print(color, color in allowed)
# red True
# yellow False
# blue TrueChecking in on a set takes roughly constant time, while on a list it scans the items one by one. For a small collection the difference is invisible, but for thousands of lookups it adds up.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Using `{}` for an empty set | You get an empty dict | Use `set()` |
| Expecting a fixed order | Output order varies | Use `sorted()` |
| Putting a list or dict in the output | `TypeError: unhashable type` | Use a tuple or `frozenset` |
| Expecting a count of items | Duplicates vanish, so `len` is smaller | Use a list, or `collections.Counter` |
Exercise
Write a set comprehension that, given words = ["Tea", "tea", "Coffee", "cocoa", "Cocoa"], produces the set of distinct lowercase words. How many items does it contain, and why is it not 5?
Show answer
{w.lower() for w in words} gives {'tea', 'coffee', 'cocoa'}, which has 3 items. Lowercasing makes "Tea" and "tea" equal, and "cocoa" and "Cocoa" equal, and a set keeps only one copy of equal values.
Exercise
What does type({n for n in range(0)}) return, and why does it differ from type({})?
Show answer
It returns <class 'set'>. The for clause makes it a set comprehension even though the range is empty, while a bare {} is always an empty dict.