A set comprehension looks almost identical to a list comprehension, but uses curly braces instead of square brackets, and, like any set, automatically deduplicates its results — if the expression produces the same value for two different items, only one copy ends up in the final set. It's useful whenever you're transforming a collection and specifically want unique results, without needing a separate call to the set constructor afterward.
1Understanding Set Comprehensions
A set comprehension looks almost identical to a list comprehension, but uses curly braces instead of square brackets, and, like any set, automatically deduplicates its results — if the expression produces the same value for two different items, only one copy ends up in the final set. It's useful whenever you're transforming a collection and specifically want unique results, without needing a separate call to the set constructor afterward.
Don't confuse an empty pair of curly braces with an empty set — a genuinely empty {} is always a dict, not a set; you need the set() constructor explicitly, or a non-empty set comprehension, to get an empty or computed set.
words = ["apple", "banana", "cherry", "date"]
first_letters = {word[0] for word in words}
print(first_letters)2Practical Example
Here is a real-world application of Set Comprehensions showing how it is used in production Python code.
numbers = [1, 2, 2, 3, 4, 4, 5]
remainders = {n % 3 for n in numbers}
print(remainders)3Best Practices
Follow these guidelines when working with Set Comprehensions:
1. Use a set comprehension instead of a list comprehension wrapped in set() when you know you only need unique results and don't need list ordering along the way
2. Reach for a set comprehension for fast membership testing on the result, since a set's membership check is average O(1) versus O(n) for a list
3. Remember curly-brace syntax with just an expression, no colon, makes a set comprehension, while adding a colon and a second expression makes a dict comprehension instead
Tip: Don't confuse an empty pair of curly braces with an empty set — a genuinely empty {} is always a dict, not a set; you need the set() constructor explicitly, or a non-empty set comprehension, to get an empty or computed set.
words = ["apple", "banana", "cherry", "date"]
first_letters = {word[0] for word in words}
print(first_letters)