How Do Sets Work in Python?
Learn how Python sets store unique hashable elements, give O(1) membership tests, and support union, intersection, difference, and frozenset with examples.
Expected Interview Answer
A Python set is an unordered collection of unique, hashable elements backed by a hash table, so membership tests and insertions run in average O(1) time. Sets automatically discard duplicates and support mathematical operations like union, intersection, and difference.
Because sets are built on hashing, elements must be immutable (hashable) — you can store numbers, strings, and tuples but not lists or dicts. Sets are mutable (you can add and remove items), while frozenset is the immutable, hashable variant that can itself live inside another set. Sets do not preserve insertion order and do not support indexing, trading ordering for very fast lookups and clean de-duplication.
- Automatic removal of duplicate values
- Average O(1) membership testing with the in operator
- Built-in union, intersection, difference and symmetric difference
- Cleaner code for de-duplication than manual loops
- frozenset provides an immutable, hashable set for use as dict keys or set members
AI Mentor Explanation
A set is like the list of unique nations in a World Cup — each country appears exactly once no matter how many players it fields. Ask 'is Australia playing?' and the answer comes instantly, without scanning every player. Adding Australia twice changes nothing, just as inserting a duplicate into a Python set leaves it unchanged because membership, not order or count, is what matters.
Step-by-Step Explanation
Step 1
Create a set
Use curly braces {1, 2, 3} or set([1, 2, 2, 3]); an empty set must be set(), since {} is a dict.
Step 2
Duplicates vanish
Adding an element already present is a no-op, so sets naturally de-duplicate any input iterable.
Step 3
Elements must be hashable
Store ints, strings, and tuples; lists and dicts raise TypeError because they are mutable and unhashable.
Step 4
Test membership
Use 'x in myset' for average O(1) lookups instead of the O(n) scan a list would need.
Step 5
Combine sets
Use union (|), intersection (&), difference (-), and symmetric difference (^) for set algebra.
What Interviewer Expects
- Sets store unique, hashable elements and are unordered
- Average O(1) membership testing thanks to hashing
- Knowledge of union, intersection and difference operations
- Difference between set (mutable) and frozenset (immutable)
- Awareness that sets do not support indexing or slicing
Common Mistakes
- Using {} to create an empty set (it creates a dict instead)
- Trying to store a list or dict in a set and hitting TypeError
- Assuming sets keep insertion order or can be indexed
- Confusing discard() (safe) with remove() (raises KeyError if missing)
- Expecting duplicate additions to raise an error rather than being ignored
Best Answer (HR Friendly)
“A Python set is a collection that automatically keeps only unique items and can instantly tell you whether something is inside it. It is great for removing duplicates and for combining groups with operations like union and intersection.”
Code Example
nums = [1, 2, 2, 3, 3, 3]
unique = set(nums) # {1, 2, 3} - duplicates removed
print(unique)
empty = set() # correct empty set ({} is a dict!)
empty.add('a')
empty.add('a') # ignored, already present
print(empty) # {'a'}
print(2 in unique) # True, average O(1) lookup
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # union -> {1, 2, 3, 4, 5, 6}
print(a & b) # intersection -> {3, 4}
print(a - b) # difference -> {1, 2}
print(a ^ b) # symmetric -> {1, 2, 5, 6}
frozen = frozenset([1, 2, 3]) # immutable + hashable
nested = {frozen, frozenset([4, 5])} # can live inside another set
print(nested)
Follow-up Questions
- Why must set elements be hashable, and which built-in types qualify?
- What is the difference between a set and a frozenset?
- How do remove() and discard() differ when the element is absent?
- Why is membership testing faster in a set than in a list?
- How would you find elements common to two lists using sets?
MCQ Practice
1. What is the average time complexity of the 'in' operator on a set?
Sets are backed by a hash table, so membership testing is average O(1), unlike a list which is O(n).
2. Which of these cannot be stored as an element of a set?
Lists are mutable and unhashable, so adding one to a set raises TypeError; tuples, ints, and strings are hashable.
3. What does the expression {1, 2} & {2, 3} evaluate to?
The & operator returns the intersection, the elements common to both sets, which is {2}.
Flash Cards
What is a Python set? — An unordered collection of unique, hashable elements backed by a hash table.
How do you create an empty set? — Use set(); the literal {} creates an empty dictionary instead.
What is a frozenset? — An immutable, hashable version of a set that can be used as a dict key or set member.
How fast is set membership testing? — Average O(1) because of hashing, versus O(n) for a list.
Name three set operations. — Union (|), intersection (&), and difference (-); also symmetric difference (^).