Sets in Python
Sets in Python
Section titled “Sets in Python”Introduction
Section titled “Introduction”A set is an unordered collection of unique, hashable elements, backed by a hash table with O(1) membership testing.
Creating Sets
Section titled “Creating Sets”# Empty set — MUST use set(), not {}!empty_set = set()empty_dict = {} # This is a dict!
# Set with elementsfruits = {"apple", "banana", "cherry"}
# From iterable (auto-removes duplicates)unique = set([1, 2, 2, 3, 3, 3])print(unique) # {1, 2, 3}Set Methods
Section titled “Set Methods”s = {1, 2, 3, 4, 5}
# Adding/Removings.add(6) # O(1)s.remove(6) # Raises KeyError if missings.discard(99) # No error if missing! ✅popped = s.pop() # Remove & return ARBITRARY element
# Checkingprint(3 in s) # True — O(1)! Fast!Set Operations
Section titled “Set Operations”A = {1, 2, 3, 4, 5}B = {4, 5, 6, 7, 8}
# Unionprint(A | B) # {1,2,3,4,5,6,7,8}print(A.union(B))
# Intersectionprint(A & B) # {4, 5}print(A.intersection(B))
# Differenceprint(A - B) # {1, 2, 3}print(A.difference(B))
# Symmetric Differenceprint(A ^ B) # {1,2,3,6,7,8}
# Subset/Supersetprint({1,2}.issubset(A)) # Trueprint(A.issuperset({1,2})) # TrueFrozen Sets
Section titled “Frozen Sets”fs = frozenset({1, 2, 3}) # Immutable set
# Can be dict key or set element!graph = { frozenset({0, 1}): "edge", frozenset({1, 2}): "edge",}Set Comprehension
Section titled “Set Comprehension”squares = {x**2 for x in range(10)}unique_vowels = {c for c in "hello world" if c in "aeiou"}Why It Matters
Section titled “Why It Matters”Sets are essential for fast membership testing, removing duplicates, and set operations (union, intersection, difference) used in data analysis.
Interview Questions
Section titled “Interview Questions”Q1: Why is x in set O(1) but x in list O(n)?
A: Sets use hash tables — hash(x) maps directly to a bucket (O(1)). Lists require linear search (O(n)).
Q2: What types can be stored in a set?
A: Only hashable types: int, float, str, tuple (of hashables), frozenset. Lists, dicts, and sets are NOT hashable.
Practice Exercises
Section titled “Practice Exercises”- Find common elements between two lists using set intersection.
- Remove duplicates from a list while preserving order.
- Use
frozensetas a dictionary key for an undirected graph.