A set comprehension creates a new set by applying an expression to each element of an iterable, with optional filtering. The syntax is {expression for item in iterable if condition}. For example, {x % 10 for x in range(100)} creates {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} — the set of last digits.
Set comprehensions automatically deduplicate results, since sets contain only unique elements. They are useful for extracting unique transformed values from a collection: {word.lower() for word in text.split()} gives the set of unique lower-cased words. Like list and dictionary comprehensions, they support multiple for clauses and if filters.
The syntax for a set comprehension ({expr for x in iterable}) looks identical to a dictionary comprehension without the colon. Python distinguishes them by the absence of a : separator. An empty set cannot be created with {} (that creates an empty dictionary) — you must use set(). Set comprehensions share the performance benefits of other comprehensions: optimised C-level iteration inside CPython.
Related terms: Set, Comprehension, List Comprehension
Discussed in:
- Chapter 6: Data Structures — List Comprehensions