Sets
Set Comprehensions
Creating sets with comprehension syntax
Interview: Shows Pythonic fluency — set comprehensions combine deduplication with transformation
Set comprehensions use {expression for item in iterable if condition} syntax to create sets concisely. They automatically handle deduplication and are often faster than building a set with add() in a loop.
Syntax
- Basic:
{x**2 for x in range(10)}→ {0, 1, 4, 9, 16, 25, 36, 49, 64, 81} - With filter:
{x for x in data if x > 0} - From string:
{c.lower() for c in text if c.isalpha()}— unique letters - Duplicates in the source are automatically eliminated in the result
Common Patterns
- Unique values: Extract unique elements with transformation
- Validation: Collect unique error types or invalid items
- Finding duplicates: Use seen-set pattern with comprehension
- Flattening:
{x for sublist in nested for x in sublist}— unique elements from nested lists
Use Cases
Extracting unique elements with transformation
Finding duplicates and common patterns
Text analysis: unique words, characters, patterns
Algorithm problems: anagram grouping, factorization
Common Mistakes
Forgetting that set comprehensions use {} while dict comprehensions use {k: v} — Python distinguishes by the colon
Using set comprehension when you need order (sets are unordered — use dict.fromkeys() for ordered unique)
Not knowing that the or-in-seen.add(x) trick works but is less readable than a loop
Overusing set comprehensions when a simple set() call on a generator would be clearer