Skip to content

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.

Beginner 8 min read·Lesson 149 of 306 in Python Programming

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

Python
unique_words = {w.lower() for w in words}
domains = {email.split("@")[1] for email in emails}
both = {x for x in a} & {x for x in b}
  • Braces, no colon.
  • Duplicates disappear.
  • Order isn't guaranteed — sort for display.

Code examples

Unique values

Python
words = ["Python", "java", "python", "C", "JAVA"]
print(sorted({w.lower() for w in words}))
print({n % 3 for n in range(10)})
Output
['c', 'java', 'python']
{0, 1, 2}

Unique e-mail domains

Python
emails = ["asha@gmail.com", "ravi@YAHOO.com", "meera@gmail.com ", "john@outlook.com"]
domains = {e.strip().lower().split("@")[1] for e in emails}
print(sorted(domains), len(domains))
Output
['gmail.com', 'outlook.com', 'yahoo.com'] 3

More examples

Comparing two groups

Python
java_class = ["Asha", "Ravi", "Meera", "John"]
python_class = ["ravi", "Priya", "john", "Kiran"]
java = {n.lower() for n in java_class}
python = {n.lower() for n in python_class}
print("both:", sorted(java & python))
print("only java:", sorted(java - python))
print("total distinct:", len(java | python))
letters = {ch for name in java_class for ch in name.lower() if ch.isalpha()}
print("letters used:", "".join(sorted(letters)))
Output
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:

TextOutput
both: ['john', 'ravi']
only java: ['asha', 'meera']
total distinct: 6
letters used: aehijmnorsv

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

print({"b", "a", "c"}) # order may vary

Prefer

print(sorted({"b", "a", "c"}))

Sets have no defined order; sort before displaying.

Unhashable elements

Avoid

{[a, b] for a, b in pairs}

Prefer

{(a, b) for a, b in pairs}

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

  1. 1
    Find the distinct file extensions in a list of file names.
  2. 2
    Find 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?
Practise this topic