Skip to content

Latest commit

Β 

History

History
128 lines (93 loc) Β· 2.89 KB

File metadata and controls

128 lines (93 loc) Β· 2.89 KB

🐍 09 – Sets

🎯 What You'll Learn

  • Create and use sets
  • Set operations (union, intersection, difference)
  • When to use sets vs lists

πŸ“Œ JS vs Python β€” Side by Side

Concept JavaScript Python
Create new Set([1,2,3]) {1, 2, 3}
Add item s.add(x) s.add(x)
Remove item s.delete(x) s.remove(x)
Check member s.has(x) x in s
Size s.size len(s)
Union new Set([...a,...b]) a | b
Intersection manual loop a & b
Difference manual loop a - b

πŸ’‘ Creating Sets

# Sets store UNIQUE values only β€” duplicates are ignored
s = {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 added
s.remove(1)       # {2, 3, 4} β€” raises KeyError if missing
s.discard(99)     # no error if 99 not in set
s.pop()           # remove and return arbitrary element
s.clear()         # empty the set

2 in s            # 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 both
a | b                    # {1,2,3,4,5,6,7,8}
a.union(b)               # same

# Intersection β€” only items in BOTH
a & b                    # {4, 5}
a.intersection(b)        # same

# Difference β€” in a but NOT in b
a - b                    # {1, 2, 3}
a.difference(b)          # same

# Symmetric difference β€” in either but NOT both
a ^ 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 list
lst = [1, 2, 2, 3, 3, 3]
unique = list(set(lst))      # [1, 2, 3]

# 2. Fast membership check
valid_roles = {"admin", "editor", "viewer"}
user_role = "admin"
if user_role in valid_roles:    # O(1) β€” instant!
    print("Access granted")

# 3. Find common items
users_a = {"Alice", "Bob", "Charlie"}
users_b = {"Bob", "Diana", "Charlie"}
both    = users_a & users_b     # {"Bob", "Charlie"}

# 4. Find unique to one group
only_a  = users_a - users_b    # {"Alice"}

⚠️ Common Mistakes

Mistake Wrong Right
Empty set {} set()
Ordered set sets are unordered use list if order matters
Duplicate handling check manually sets handle it automatically

πŸ”— Next Lesson

πŸ‘‰ 10 – Functions