Sub topic 6
Building Sets with Set Comprehensions
A set comprehension builds a set from any iterable in one expression. You write it like a list comprehension, but with curly braces and a single output expression. This chapter covers the syntax, what changes because the result is a set, and the errors that come from sets being unordered and hash-based.
What this chapter assumes
You should already know:
- how
forloops andrangework - the basic behaviour of lists, dictionaries, and sets
- boolean expressions and comparison operators
- how to build a list with a loop and
append
You should also have seen a list comprehension, [expression for item in iterable], and a trailing if filter. Everything here reuses that grammar.
The syntax
A set comprehension has the same parts as a list comprehension. Only the brackets differ.
words = ["apple", "banana", "cherry"]
unique_lengths = {len(w) for w in words}
print(unique_lengths) # {5, 6}The loop that does the same job is:
words = ["apple", "banana", "cherry"]
unique_lengths = set()
for w in words:
unique_lengths.add(len(w))
print(unique_lengths) # {5, 6}The loop starts with an empty set and calls add once per item. The comprehension collapses that into one expression. "banana" and "cherry" both have length 6. The second 6 is already in the set, so add does nothing for it. The comprehension behaves the same way.
The general form is:
{expression for item in iterable if condition}The if condition part is optional. The expression runs once for each item that passes the condition, and each result is added to the set.
What makes a set comprehension different
A set comprehension is a list comprehension with three changes in the result.
- Duplicates disappear. Two items count as the same if they hash equally and compare equal with
==. - Order is not part of the result. A set has no positional index. You can't write
result[0], and you shouldn't depend on the order in which elements print. - Every element must be hashable. Lists, dicts, and other sets can't be elements.
The sections below take these in turn.
Removing duplicates while transforming
The most common use is normalising values and collapsing the ones that become equal.
emails = ["[email protected]", "[email protected]", "[email protected]", "[email protected]"]
unique = {e.lower() for e in emails}
print(sorted(unique)) # ['[email protected]', '[email protected]']Four strings go in and two come out, because the transformation (lower()) runs before the set compares the values. The example prints sorted(unique) because iterating a set of strings can give a different order from one run to the next. Python randomises string hashes at startup. Sort whenever you print or compare a set of strings.
Compare this with the list version.
emails = ["[email protected]", "[email protected]", "[email protected]", "[email protected]"]
as_list = [e.lower() for e in emails]
print(as_list) # ['[email protected]', '[email protected]', '[email protected]', '[email protected]']The list keeps all four items in their original order. The set keeps two and gives up the order.
Filtering
A trailing if works as it does in a list comprehension. It decides which items reach the output expression.
numbers = [3, 8, 12, 7, 8, 3, 20]
big_remainders = {n % 5 for n in numbers if n > 5}
print(sorted(big_remainders)) # [0, 2, 3]The filter drops 3, 3, and the second 3 first. The remaining values are 8, 12, 7, 8, and 20. Their remainders modulo 5 are 3, 2, 2, 3, and 0. Collapsing duplicates gives {0, 2, 3}.
The filter and the deduplication are independent. The filter acts on the source items, and the set acts on the outputs. An item can pass the filter and still add nothing, because its output is already in the set.
The empty set trap
Curly braces with nothing inside create an empty dictionary, not an empty set. This is a quirk of the literal syntax, and a comprehension doesn't change it.
words = ["apple", "banana", "cherry"]
unique_lengths = {len(w) for w in words}
print(unique_lengths) # {5, 6}
empty = set() # {} would create an empty dict, not an empty set
print(type({}), type(empty)) # <class 'dict'> <class 'set'>A comprehension that matches nothing is not affected. It returns an empty set, because the for keyword inside the braces makes Python parse it as a set comprehension.
none_match = {n for n in range(5) if n > 100}
print(none_match) # set()
print(type(none_match)) # <class 'set'>The trap only applies when you write the empty literal yourself. To start with an empty set, use set().
Hashable elements only
A set stores each element by its hash. Mutable built-in containers such as lists don't have a stable hash, so Python refuses them.
rows = [[1, 2], [2, 1], [1, 2]]
try:
result = {r for r in rows}
except TypeError as error:
print(error) # unhashable type: 'list'The usual fix is to convert each element to an immutable equivalent, often a tuple.
rows = [[1, 2], [2, 1], [1, 2]]
as_tuples = {tuple(r) for r in rows}
print(sorted(as_tuples)) # [(1, 2), (2, 1)]
order_blind = {tuple(sorted(r)) for r in rows}
print(order_blind) # {(1, 2)}The first set treats [1, 2] and [2, 1] as different rows. The second sorts each row before converting it, so both rows become (1, 2) and collapse into one. If you need a set whose elements are themselves sets, use frozenset for the inner values.
groups = [{"a", "b"}, {"b", "a"}, {"c"}]
distinct_groups = {frozenset(g) for g in groups}
print(len(distinct_groups)) # 2Equality decides what counts as a duplicate
Duplicates are decided by hash and ==, not by type. Python treats 1, 1.0, and True as equal with equal hashes, so they collapse.
mixed = {x for x in [1, 1.0, True, 2]}
print(mixed) # {1, 2}When several equal items arrive, the set keeps the first one it saw. Here that is the integer 1. This matters when you deduplicate data of mixed types, such as values read from a loosely typed file. If True and 1 mean different things in your data, a set will hide the difference.
Using the result: membership and set algebra
A common reason to build a set is fast membership testing. Checking x in some_set takes roughly constant time on average. Checking x in some_list scans the list. Build the set once, outside any loop that uses it.
banned = {w.lower() for w in ["Spam", "SCAM", "phish"]}
messages = ["Hello", "spam offer", "SCAM", "Lunch?"]
clean = [m for m in messages if m.lower() not in banned]
print(clean) # ['Hello', 'spam offer', 'Lunch?']Note that "spam offer" survives. The test compares the whole string with the set elements, and "spam offer" is not equal to "spam". A set tests whole-element equality, not substrings.
Set comprehensions also combine well with the set operators & (intersection), | (union), and - (difference).
evens = {n for n in range(10) if n % 2 == 0}
threes = {n for n in range(10) if n % 3 == 0}
print(sorted(evens & threes)) # [0, 6]
print(sorted(evens | threes)) # [0, 2, 3, 4, 6, 8, 9]
print(sorted(evens - threes)) # [2, 4, 8]Set comprehension or `set(...)` on a generator
These two lines build the same set:
words = ["apple", "banana", "cherry"]
a = {len(w) for w in words}
b = set(len(w) for w in words)
print(a == b) # TrueThe first is idiomatic and reads more directly. The second creates a generator expression and passes it to the set constructor, which adds a function call. Prefer the braces. The constructor form is useful when you already have an iterable and no transformation, such as set(words). A comprehension adds nothing there, so don't write {w for w in words}.
Choosing between a set and a list
Use a set comprehension when:
- you only care whether a value is present, not how many times it appears
- you will do membership tests or set algebra on the result
- you need the distinct values, and order does not matter
Use a list comprehension when:
- order matters
- duplicates are meaningful, for example when you will count them
- you need to index or slice the result
If you need distinct values in their original order, a set comprehension is the wrong tool. Use dict.fromkeys, because dictionaries keep insertion order.
items = ["b", "a", "b", "c", "a"]
ordered_unique = list(dict.fromkeys(items))
print(ordered_unique) # ['b', 'a', 'c']Side effects and readability
A comprehension should describe the set you want, not perform actions. Avoid calling functions that print, write files, or modify other objects inside the expression. The add method returns None, so using it inside a comprehension gives you nothing useful. If the work is mostly side effects, a plain for loop states that intent better.
Keep the expression and the condition short. If a set comprehension needs several clauses and a long condition, break it into steps with named intermediate values, or use a loop with seen.add(...).
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Writing `{}` to start an empty set | You get an empty dict | Use `set()` |
| Relying on printed order | Output order can differ between runs for strings | Use `sorted(...)` when printing or comparing |
| Putting lists in the output expression | `TypeError: unhashable type: 'list'` | Convert to `tuple` or `frozenset` |
| Using `{k: v for ...}` and expecting a set | The colon makes it a dict comprehension | Remove the `: v` part |
| Indexing the result with `s[0]` | `TypeError`, sets are not subscriptable | Convert with `sorted(s)` or `list(s)` |
| Mixing `1`, `1.0`, and `True` | They collapse into one element | Normalise the types first |
Exercises
Exercise
Write a set comprehension that takes names = ["Ada", "ada", "Grace", "GRACE", "Linus"] and produces the set of distinct names in lowercase. What are its elements, sorted?
Show answer
{n.lower() for n in names}. Sorted, the elements are ['ada', 'grace', 'linus'].
Exercise
The following code fails. Explain why and fix it so it returns the set of distinct pairs, treating [1, 2] and [2, 1] as the same pair.
pairs = [[1, 2], [2, 1], [3, 4]]
result = {p for p in pairs}
Show answer
Lists are mutable and unhashable, so they can't be set elements, which raises TypeError: unhashable type: 'list'. Convert each pair to a sorted tuple: {tuple(sorted(p)) for p in pairs}. This gives {(1, 2), (3, 4)}.
Exercise
What does {x for x in [1, 1.0, True, 0, False]} contain, and why?
Show answer
It contains {1, 0}. The values 1, 1.0, and True are equal and hash the same, so only the first one seen (1) is kept. 0 and False are likewise equal, so only 0 is kept.
Exercise
You have lines (a list of strings) and want to keep only lines whose lowercase form is not in a block list ["spam", "scam"]. Write the code so the block list is converted once, not on every line.
Show answer
blocked = {w.lower() for w in ["spam", "scam"]} followed by kept = [line for line in lines if line.lower() not in blocked]. The set is built once outside the loop, and each membership test is a fast hash lookup.