Module 10 · Comprehensions and Advanced Iteration — topic 5 of 13
Set comprehensions
Building sets with {expression for ...} to collect unique values, normalising data before de-duplication, and comparing results with set operations.
Learning objectives
- Write set comprehensions to collect unique values
- Normalise values before de-duplicating
- Combine set comprehensions with set operations
Definition
A set comprehension is an expression {expression for item in iterable} that evaluates the expression for each item and collects the distinct results into a new set.
Introduction
{word.lower() for word in text.split()} gives every distinct word, regardless of capitalisation. Set comprehensions are the quickest way to answer 'which different values occur?'.
Why it matters
De-duplicating emails, tags, domains or categories is a constant need, and sets make membership tests and comparisons fast.
Detailed explanation
The syntax uses braces without a colon: {x % 3 for x in range(10)} is {0, 1, 2}.
Duplicates are removed automatically; the result size is the number of distinct values.
Sets are unordered: don't rely on the order in which a set prints. Use sorted(...) when you need a stable order.
Elements must be hashable (numbers, strings, tuples) — you can't put lists or dictionaries in a set.
Normalise before collecting so equivalent values merge: strip spaces, lower-case, remove punctuation.
Results can be combined with |, & and - to find unions, common values and differences.
Membership tests on a set (x in s) take roughly constant time however large the set is, whereas the same test on a list scans every element. So a set comprehension is often the first step in an efficient program: build the set of known values once, then check thousands of items against it quickly.
Syntax
- Braces, no colon.
- Duplicates disappear.
- Order isn't guaranteed — sort for display.
Code examples
Unique values
['c', 'java', 'python']
{0, 1, 2}Unique e-mail domains
['gmail.com', 'outlook.com', 'yahoo.com'] 3
More examples
Comparing two groups
both: ['john', 'ravi'] only java: ['asha', 'meera'] total distinct: 6 letters used: aehijmnorsv
Step-by-step explanation
- Both name lists are normalised to lower case so 'Ravi' and 'ravi' match.
- & finds students in both classes, - those only in Java, | everyone.
- The last comprehension uses two for clauses to collect the distinct letters of all names.
Expected output
Running “Comparing two groups” prints exactly:
Practical applications
- Finding unique visitors, tags or product categories.
- Detecting overlap between two mailing lists.
Best practices
- Normalise values before de-duplicating.
- Sort sets when output must be reproducible.
- Use set operations instead of nested loops for comparisons.
Common mistakes
Printing a set and expecting order
Avoid
Prefer
Sets have no defined order; sort before displaying.
Unhashable elements
Avoid
Prefer
Lists can't be set elements; use tuples.
Important notes
- Small sets of integers often print in increasing order, but that's an implementation detail — never rely on it.
Key takeaways
- {expr for x in it} builds a set of distinct values.
- Elements must be hashable.
- Sets are unordered; use sorted() for display.
Try it yourself
- 1Find the distinct file extensions in a list of file names.
- 2Find which words appear in both of two sentences, ignoring case.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?