Page9/20
Dictionaries & Sets Β· Page 2 of 2
Sets β Unique Collections
Sets β Unique Collections
A set is an unordered collection of unique values. Use sets when you only care about membership ("Is this item here?") and need to eliminate duplicates.
fruit_colors = {"red", "green", "yellow", "red"}
# Set automatically removes duplicate "red"
# Result: {"red", "green", "yellow"}
Creating Sets
s = {1, 2, 3} # set literal
s = set([1, 2, 2, 3]) # from list (removes duplicates)
s = set("hello") # from string β {'h', 'e', 'l', 'o'}
Set Operations (for Data Filtering)
users_bought_a = {1, 3, 5, 7}
users_bought_b = {2, 3, 6, 7, 8}
# Intersection: bought BOTH A and B
users_bought_a & users_bought_b # {3, 7}
# Union: bought EITHER A or B
users_bought_a | users_bought_b # {1, 2, 3, 5, 6, 7, 8}
# Difference: bought A but NOT B
users_bought_a - users_bought_b # {1, 5}
Set Methods
s = {1, 2, 3}
s.add(4) # {1, 2, 3, 4}
s.remove(2) # {1, 3, 4} β raises KeyError if not found
s.discard(2) # {1, 3, 4} β no error if not found
s.pop() # remove & return arbitrary element
1 in s # True (O(1) lookup!)
When to use sets: Filtering duplicate IDs, finding common elements between datasets, membership testing.
main.py
Loading...
OUTPUT
βΆClick "Run Code" to executeβ¦