🕯️ Magic Note
Sets in Python don’t allow duplicate values. When you create a set from a list, duplicates vanish automatically. No need to write a loop or check conditions manually.
- Original list can contain any hashable type (strings, numbers, tuples)
- The result will contain each element only once
- Order is NOT preserved (sets are unordered)
| Input | Output |
|---|---|
| [1, 2, 2, 3, 3, 3] | [1, 2, 3] |
| [“apple”, “banana”, “apple”] | [“apple”, “banana”] |
| [True, False, True, True] | [True, False] |
Python
# Remove duplicates from a list of numbers
numbers = [4, 2, 4, 1, 2, 4, 3]
unique_numbers = list(set(numbers))
print(unique_numbers)
# Output: [1, 2, 3, 4] (order may vary)
Python
# Remove duplicates from a list of strings
words = [“hello”, “world”, “hello”, “python”]
unique_words = list(set(words))
print(unique_words)
# Output: [“python”, “world”, “hello”] (order may vary)
Python
# Watch out: True equals 1 in Python sets
mixed = [1, “1”, 1, “1”, True]
unique_mixed = list(set(mixed))
print(unique_mixed)
# Output: [1, “1”] (True is treated as 1 and removed as duplicate)
- Expecting order preservation, sets don’t maintain insertion order
- Using on nested lists TypeError: unhashable type: ‘list’
- Forgetting that True and 1 are considered equal in sets
⚡ Whisper
Duplicates are just noise. Silence them. Each echo deserves to be heard only once. The set hears all voices and chooses only the first whisper of each.