🕯️ Magic Note
A set in Python cannot contain duplicate values. When you iterate through a string and add each character to a set, each character is stored only once regardless of how many times it appears. The set comprehension creates this collection in one clean line. Then len() reveals how many unique characters survived the filtering.
- Set comprehensions use curly braces like dictionary comprehensions but without key-value pairs
- The result is a set containing unique elements from the iterable
- Order is not preserved because sets are unordered
- Equivalent to len(set(“COFFEE”)) which is simpler for this specific use case
| String | Set of Unique Characters | Count |
|---|---|---|
| “COFFEE” | {“C”, “O”, “F”, “E”} | 4 |
| “BANANA” | {“B”, “A”, “N”} | 3 |
| “MISSISSIPPI” | {“M”, “I”, “S”, “P”} | 4 |
| “PYTHON” | {“P”, “Y”, “T”, “H”, “O”, “N”} | 6 |
| “aaa” | {“a”} | 1 |
Python
# Count unique characters in a word
word = “COFFEE”
unique_count = len({c for c in word})
print(unique_count)
# Output: 4
Python
# Simpler way: using set() directly
word = “COFFEE”
unique_count = len(set(word))
print(unique_count)
# Output: 4
# set(word) does the same as the comprehension
Python
# Filtering before counting: only letters
text = “C0FF33!”
letters_only = {c for c in text if c.isalpha()}
print(letters_only)
# Output: {“C”, “F”}
print(len(letters_only))
# Output: 2
- Confusing set comprehension {c for c in word} with dictionary comprehension which requires key-value pairs
- Forgetting that sets are unordered, expecting the count to preserve the original order of characters
- Using set comprehension when set(word) would be simpler and more readable for basic unique character extraction
⚡ Whisper
The coffee cup holds many sips, but only a few flavors. The word echoes with repetition, but the silence after reveals the truth. Count what remains when the noise is gone. That is the measure of essence.