Topic 52 of 64
Set Uniqueness
Overview
Sets are unordered collections of unique, hashable elements backed by a hash table. They provide O(1) membership testing and automatic deduplication — making them indispensable for uniqueness checks and fast lookups.
Syntax
python
# Creation
s = {1, 2, 3, 3, 2} # {1, 2, 3} — duplicates removed
empty = set() # {} is a dict, NOT a set!
# Add/remove
s.add(4)
s.remove(1) # raises KeyError if missing
s.discard(99) # safe remove (no error)
# Membership — O(1)
3 in s # True
5 in s # False
# Deduplication pattern
unique = list(set([1, 2, 2, 3, 3, 3])) # [1, 2, 3]Common Pitfalls
- Sets are unordered — do not rely on any specific iteration order.
- Only hashable (immutable) types can be set elements — lists and dicts cannot be added to sets.
- Interview tip: Checking 'x in list' is O(n); 'x in set' is O(1). For repeated lookups, always convert the list to a set first.
Real-World Example
Find duplicate emails in a registration list
example
python
def find_duplicates(emails: list[str]) -> set[str]:
seen: set[str] = set()
duplicates: set[str] = set()
for email in emails:
email = email.lower()
if email in seen:
duplicates.add(email)
else:
seen.add(email)
return duplicates
emails = ["a@x.com", "B@x.com", "b@x.com", "c@x.com"]
print(find_duplicates(emails)) # {'b@x.com'}