You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# Sets store UNIQUE values only β duplicates are ignoreds= {1, 2, 3, 3, 2, 1}
print(s) # {1, 2, 3}# From a list β great for removing duplicates!lst= [1, 2, 2, 3, 3, 3, 4]
unique=set(lst) # {1, 2, 3, 4}# Empty set β MUST use set(), not {} (that creates empty dict)empty=set() # β empty= {} # β this is an empty DICT
π‘ Set Methods
s= {1, 2, 3}
s.add(4) # {1, 2, 3, 4}s.add(2) # {1, 2, 3, 4} β no duplicate addeds.remove(1) # {2, 3, 4} β raises KeyError if missings.discard(99) # no error if 99 not in sets.pop() # remove and return arbitrary elements.clear() # empty the set2ins# True β O(1) lookup (much faster than list!)len(s) # count
π‘ Set Operations
a= {1, 2, 3, 4, 5}
b= {4, 5, 6, 7, 8}
# Union β all items from botha|b# {1,2,3,4,5,6,7,8}a.union(b) # same# Intersection β only items in BOTHa&b# {4, 5}a.intersection(b) # same# Difference β in a but NOT in ba-b# {1, 2, 3}a.difference(b) # same# Symmetric difference β in either but NOT botha^b# {1,2,3,6,7,8}a.symmetric_difference(b) # same# Subset / Superset
{1,2}.issubset({1,2,3}) # True
{1,2,3}.issuperset({1,2}) # True
{1,2}.isdisjoint({3,4}) # True β no common elements
π‘ Common Use Cases
# 1. Remove duplicates from a listlst= [1, 2, 2, 3, 3, 3]
unique=list(set(lst)) # [1, 2, 3]# 2. Fast membership checkvalid_roles= {"admin", "editor", "viewer"}
user_role="admin"ifuser_roleinvalid_roles: # O(1) β instant!print("Access granted")
# 3. Find common itemsusers_a= {"Alice", "Bob", "Charlie"}
users_b= {"Bob", "Diana", "Charlie"}
both=users_a&users_b# {"Bob", "Charlie"}# 4. Find unique to one grouponly_a=users_a-users_b# {"Alice"}