Collect Unique Results with Set Comprehensions
Core idea
A set comprehension uses {expression for item in iterable} without a colon. It collects distinct hashable results, not necessarily distinct input items. The set has no guaranteed iteration order; use sorted() when comparable elements must be displayed in a predictable order.
codes = [10, 12, 15, 18]print(sorted({n % 3 for n in codes}))Different codes may yield equal remainders, which collapse into one element.
Filter and deduplicate
values = [0, 4, 4, -2, 7]print(sorted({n for n in values if n > 0}))Only positive values remain, and repeated fours appear once.
Check empty result type
result = {n for n in [1, 2] if n > 5}print(result == set())print(result == {})An empty set comprehension produces a set, while {} is an empty dictionary.
Common mistake
Lists are not hashable and cannot be set elements. Convert a list of hashable items to a tuple when an immutable sequence is appropriate.
Practice
Collect the unique last digits of [21, 31, 42, 52] and display them sorted.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Set transformations
Check your understanding of set comprehensions.
What is printed?
print(sorted({n % 2 for n in [3, 5, 8]}))What is printed?
print({n for n in []} == set())What is printed?
print(sorted({n for n in [2, 0, 2] if n > 0}))Why sort numeric set results before displaying them?