Learning

Sets & Set Operations

Sets & Set Operations

Creating Sets

python
# From literals (curly braces) fruits = {'apple', 'banana', 'cherry'} # From constructor nums = set([1, 2, 2, 3, 3, 3]) # {1, 2, 3} (duplicates removed!) # Empty set (MUST use set()) empty = set() # empty = {} # ❌ This creates an EMPTY DICT! # From strings chars = set('hello') # {'h', 'e', 'l', 'o'} (unordered, no duplicate 'l')

Modifying Sets

python
s = {1, 2, 3} s.add(4) # {1, 2, 3, 4} s.add(2) # {1, 2, 3, 4} (no change, already exists) s.update([5, 6]) # {1, 2, 3, 4, 5, 6} s.remove(3) # {1, 2, 4, 5, 6} (KeyError if not found!) s.discard(99) # No error if not found (safe!) popped = s.pop() # Removes & returns a RANDOM element s.clear() # Empties the set

Mathematical Operations

python
a = {1, 2, 3, 4} b = {3, 4, 5, 6} # Union (all elements from both) print(a | b) # {1, 2, 3, 4, 5, 6} print(a.union(b)) # Same # Intersection (common elements) print(a & b) # {3, 4} print(a.intersection(b)) # Same # Difference (in a but NOT in b) print(a - b) # {1, 2} print(a.difference(b)) # Same # Symmetric Difference (in either, but NOT in both) print(a ^ b) # {1, 2, 5, 6} print(a.symmetric_difference(b)) # Same # Subset & Superset print({1, 2} <= a) # True (subset) print(a >= {1, 2}) # True (superset) print(a == {1,2,3,4}) # True (equal)

Frozen Sets

python
# Immutable set — can be used as dict key or inside another set fs = frozenset([1, 2, 3]) # fs.add(4) # AttributeError! # Valid dict key coords = {frozenset([1, 2]): 'Pair 1-2'} # Valid set element nested = {frozenset([1, 2]), frozenset([3, 4])}
Key Rules
  • •Empty set MUST be created with set() — {} creates an empty dictionary
  • •Sets are UNORDERED — don't rely on indexing or slicing (they don't support it)
  • •remove() raises KeyError if element missing; discard() does NOT raise an error
  • •Use | for union, & for intersection, - for difference, ^ for symmetric difference
  • •frozenset is the immutable version — use it when you need a set as a dictionary key
Your Task

Create a function `analyze_sets(a, b)` that accepts two lists, converts them to sets, and returns a dictionary containing the counts of: 'union', 'intersection', 'only_in_a', 'only_in_b'. Create another function `remove_duplicates_keep_order(lst)` that removes duplicates while preserving insertion order (HINT: use a set to track seen items, but build a list for output).

EditorPython · JSX
PreviewUpdates on Run Tests
Loading preview…
Tests
Should define analyze_sets function
Should convert inputs to sets
Should use set operators (&, |, -)
Should define remove_duplicates_keep_order
Should use a set for seen items tracking
Should append to a list to preserve order