🕯️ Magic Note
The star operator * unpacks an iterable. When used inside a list literal [*iterable], it spreads the elements of the iterable into a new list. Here, *’cheesecake’ would unpack the string into individual characters, but with duplicates. Wrapping it in {} first creates a set, removing duplicates. Then the outer star unpacks the unique set into a list.
- The inner star unpacks the string into individual characters
- Curly braces turn those characters into a set, removing duplicates
- The outer star unpacks the set elements
- Square brackets collect everything into a final list
| Expression | Result | Explanation |
|---|---|---|
| [*’abc’] | [‘a’,’b’,’c’] | Unpacks string into list |
| {*’abca’} | {‘a’,’b’,’c’} | Creates set of unique chars |
| [*{*’cheesecake’}] | [‘c’,’h’,’e’,’s’,’a’,’k’] | Unique chars as list |
| list(set(‘cheesecake’)) | [‘c’,’h’,’e’,’s’,’a’,’k’] | Same result, more readable |
Python
# The complete spell: unique letters as a list
word = “cheesecake”
unique_letters = [*{*word}]
print(unique_letters)
# Output: [‘c’, ‘h’, ‘e’, ‘s’, ‘a’, ‘k’] (order may vary)
Python
# Breaking it down step by step
word = “cheesecake”
step1 = {*word}
print(f”Set of unique letters: {step1}”)
step2 = [*step1]
print(f”List from set: {step2}”)
# Output: Set of unique letters: {‘c’, ‘h’, ‘e’, ‘s’, ‘a’, ‘k’}
# Output: List from set: [‘c’, ‘h’, ‘e’, ‘s’, ‘a’, ‘k’]
Python
# The readable alternative
word = “cheesecake”
unique_letters = list(set(word))
print(unique_letters)
# Output: [‘c’, ‘h’, ‘e’, ‘s’, ‘a’, ‘k’] (order may vary)
# Same result, easier to understand
- Forgetting that the outer stars are needed for unpacking, writing [{*’cheesecake’}] puts the set itself inside a list instead of its elements
- Assuming the output order matches the original word, sets are unordered so the list order is arbitrary
- Overcomplicating code when list(set()) would be clearer and more maintainable
⚡ Whisper
Layers peel away like the skin of an onion. The string cracks open. Duplicates fade. A set holds what remains. Stars unpack the essence. Brackets bind the silence into a list. One line. Many layers. Pure magic.