Sub topic 9
Set comprehensions
A set comprehension builds a set from an expression in one line. This chapter assumes you know how to create sets, that set elements must be hashable, and how list comprehensions work. The syntax is the same as for lists, with curly braces instead of square brackets.
The basic form
squares = {n * n for n in range(-3, 4)}
print(sorted(squares)) # [0, 1, 4, 9]The range produces -3 to 3. Both -3 and 3 square to 9, and both -2 and 2 square to 4. The set keeps one copy of each value, so seven inputs produce four elements. A list comprehension would have returned all seven results.
The general shape is:
{expression for item in iterable if condition}The if clause is optional. The expression result must be hashable, because it becomes a set element.
Filtering and transforming
Add a condition to keep only some items. You can also transform each item before it is stored.
words = ["Apple", "banana", "apple", "Cherry", "BANANA", "fig"]
lengths = {len(w) for w in words}
print(sorted(lengths)) # [3, 5, 6]
normalized = {w.lower() for w in words if len(w) > 3}
print(sorted(normalized)) # ['apple', 'banana', 'cherry']The second comprehension drops "fig" because of the filter. It then lowercases the rest, so "Apple" and "apple" collapse into one element. Normalizing inside the expression is a common way to deduplicate data that differs only in case or whitespace.
How it runs
Multiple loops and nested conditions
A comprehension can have more than one for clause. The clauses nest from left to right, like nested loops.
rows = [[1, 2, 2], [2, 3], [3, 3, 4]]
flat = {value for row in rows for value in row}
print(sorted(flat)) # [1, 2, 3, 4]
even_pairs = {(a, b) for a in range(3) for b in range(3) if (a + b) % 2 == 0}
print(sorted(even_pairs))
# [(0, 0), (0, 2), (1, 1), (2, 0), (2, 2)]The tuples in even_pairs are valid elements because tuples of numbers are hashable. Using a list [a, b] there would raise TypeError: unhashable type: 'list'.
Comprehension, set(), or dict.fromkeys
A set comprehension and set() applied to a generator expression give the same result. The comprehension is shorter and avoids an extra function call.
data = [1, 2, 3, 4, 5, 6]
a = {n % 3 for n in data}
b = set(n % 3 for n in data)
print(a == b) # TrueIf you need first-seen order, a set is the wrong tool. Use list(dict.fromkeys(...)) instead, as in this earlier example from the chapter on deduplication. You can also combine them, for example list(dict.fromkeys(w.lower() for w in words)).
Common mistakes
- Writing
{}for an empty result. A comprehension always produces a set, even when nothing passes the filter. The result isset(), not{}. - Using
{k: v for ...}by accident. Adding a colon makes it a dict comprehension.{x for ...}is a set, and{x: y for ...}is a dict. - Expecting order. Do not rely on the order of elements. Wrap the result in
sorted()when you print it or compare output. - Producing unhashable values. Lists, dicts and other sets cannot be elements. Convert lists to tuples, or inner sets to
frozenset.
none_match = {n for n in range(5) if n > 10}
print(none_match) # set()
print(type(none_match)) # <class 'set'>
groups = {frozenset(pair) for pair in [(1, 2), (2, 1), (3, 4)]}
print(len(groups)) # 2, because (1, 2) and (2, 1) give equal frozensetsThe last example shows a practical use of frozenset. Two orderings of the same pair become one element, which a plain tuple would not do.
Summary of the syntax
| Form | Result |
|---|---|
| `{x for x in it}` | set of every distinct `x` |
| `{x for x in it if cond}` | set of distinct `x` that pass `cond` |
| `{f(x) for x in it}` | set of distinct transformed values |
| `{x for a in A for x in a}` | flattened set from nested iterables |
Exercise
Given emails = ["[email protected]", "[email protected] ", "[email protected]", "[email protected]"], write a set comprehension that returns the distinct addresses after stripping whitespace and lowercasing. How many elements does it have?
Show answer
{e.strip().lower() for e in emails} gives {"[email protected]", "[email protected]"}, so it has 2 elements.
Exercise
Why does {[a, b] for a in range(2) for b in range(2)} fail, and how do you fix it?
Show answer
List elements are unhashable, so Python raises TypeError: unhashable type: 'list'. Use tuples instead: {(a, b) for a in range(2) for b in range(2)}.