Strings & Data Structures
Sets
Complete lesson for Sets using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.
Basics — Sets
Section: Strings & Data Structures. Python sets: unordered collections of unique hashable elements — math ops, methods, and membership tests.
What is a set?
- A set is an unordered collection of unique hashable elements.
- Create with
{1, 2, 3}orset(iterable). Empty set must beset()—{}is an empty dict. - Duplicates are dropped automatically on construction.
- Real life: unique visitor IDs, tags on a post, students enrolled in a course.
s = {1, 2, 2, 3}
print(sorted(s), type(s).__name__)
# Output:
# [1, 2, 3] set Unordered and deterministic printing
- Sets do not preserve insertion order for teaching/output guarantees across versions/platforms in interview code.
- Always
print(sorted(s))(or sort another way) when you need stable demo output. - Equality of sets ignores order:
{1, 2} == {2, 1}isTrue. - There is no indexing:
s[0]raisesTypeError.
s = {"b", "a", "c"}
print(sorted(s))
# Output:
# ['a', 'b', 'c'] Built-in functions that work on sets
- These are **built-in functions** (not set methods). Call them as
len(s), nots.len(). - For stable demo/output order, wrap with
sorted(s)— sets are unordered for teaching purposes.
| Function | What it does | Example | Result |
|---|---|---|---|
len(s) | Number of unique elements | len({1, 2, 2, 3}) | 3 |
set(iterable) | Build a set (drops duplicates) | set([1, 2, 2, 3]) | {1, 2, 3} |
frozenset(iterable) | Immutable set | frozenset([1, 2]) | frozenset({1, 2}) |
sorted(s) | Sorted **list** of elements | sorted({"b", "a"}) | ["a", "b"] |
list(s) | Convert to list (order not meaningful) | list({1, 2}) | a 2-item list |
min(s) / max(s) | Smallest / largest element | min({3, 1, 2}) | 1 |
sum(s) | Sum of numbers | sum({1, 2, 3}) | 6 |
any(s) / all(s) | Truthy checks | all({1, 2, 3}) | True |
isinstance(s, set) | Type check | isinstance({1}, set) | True |
enumerate(sorted(s)) | Indexed walk (after sorting) | list(enumerate(sorted({2,1}))) | [(0, 1), (1, 2)] |
set methods — add and remove
add(x)inserts one element.update(iterable)inserts many.remove(x)raisesKeyErrorif missing;discard(x)stays quiet.pop()removes an arbitrary element (do not rely on which).clear()empties the set.- Only hashable objects can be added (no lists, no dicts, no raw sets).
| Method | What it does | Example | Notes |
|---|---|---|---|
s.add(x) | Insert one element | {1, 2}.add(3) | No-op if already present |
s.update(iterable) | Insert many elements | {1}.update([2, 3]) | Also |= |
s.remove(x) | Remove x or error | {1, 2}.remove(2) | Raises KeyError if missing |
s.discard(x) | Remove x if present | {1, 2}.discard(9) | Quiet if missing |
s.pop() | Remove and return an arbitrary element | {1, 2}.pop() | Do not rely on which |
s.clear() | Remove all elements | {1, 2}.clear() | Becomes set() |
s.copy() | Shallow copy | t = s.copy() | New set object |
s = {1, 2}
s.add(3)
s.discard(9)
s.remove(2)
print(sorted(s))
# Output:
# [1, 3] Set algebra operators and methods
- Union:
a | bora.union(b)— elements in either. - Intersection:
a & bora.intersection(b)— elements in both. - Difference:
a - bora.difference(b)— inabut notb. - Symmetric difference:
a ^ b— in one set but not both.
| Operation | Operator | Method | Example result |
|---|---|---|---|
| Union | a | b | a.union(b) | {1,2,3} | {3,4} → {1,2,3,4} |
| Intersection | a & b | a.intersection(b) | {1,2,3} & {3,4} → {3} |
| Difference | a - b | a.difference(b) | {1,2,3} - {3,4} → {1,2} |
| Sym. difference | a ^ b | a.symmetric_difference(b) | {1,2,3} ^ {3,4} → {1,2,4} |
| In-place union | a |= b | a.update(b) | Mutates a |
| In-place intersection | a &= b | a.intersection_update(b) | Mutates a |
| In-place difference | a -= b | a.difference_update(b) | Mutates a |
| In-place sym. diff | a ^= b | a.symmetric_difference_update(b) | Mutates a |
a = {1, 2, 3}
b = {3, 4}
print(sorted(a | b))
print(sorted(a & b))
print(sorted(a - b))
print(sorted(a ^ b))
# Output:
# [1, 2, 3, 4]
# [3]
# [1, 2]
# [1, 2, 4] Relation tests
a <= b/a.issubset(b)— every element ofais inb.a >= b/a.issuperset(b)—acontains every element ofb.a.isdisjoint(b)— no common elements.- Proper subset uses
<(subset and not equal).
| Test | Operator | Method | Meaning |
|---|---|---|---|
| Subset | a <= b | a.issubset(b) | Every element of a is in b |
| Proper subset | a < b | — | Subset and not equal |
| Superset | a >= b | a.issuperset(b) | a contains every element of b |
| Proper superset | a > b | — | Superset and not equal |
| Disjoint | — | a.isdisjoint(b) | No common elements |
| Membership | x in s | — | Average O(1) lookup |
a = {1, 2}
b = {1, 2, 3}
print(a <= b, a.isdisjoint({4}), a < b)
# Output:
# True True True Membership and uniqueness
x in sis average O(1) — the main reason to use sets.- Deduplicate a list:
list(set(a))loses order; uselist(dict.fromkeys(a))to keep order. - Convert to set for fast lookups when checking many candidates against a collection.
- Elements must be hashable: ints, strs, frozensets, tuples of hashables.
| Need | Prefer |
|---|---|
| Fast membership | x in set_of_items |
| Unique values (order OK to lose) | set(items) |
| Unique values (keep order) | list(dict.fromkeys(items)) |
| Immutable unique group as a key | frozenset(items) |
set APIs — overview cheat sheet
- Use sets for uniqueness and fast
inchecks; use lists when order or duplicates matter.
| Category | Common APIs | Use when |
|---|---|---|
| Built-ins | len, set, frozenset, sorted, min, max, sum | Create, measure, display |
| Mutate | add, update, remove, discard, pop, clear | Grow or shrink a set |
| Algebra | | & - ^, union, intersection, … | Combine sets mathematically |
| Relations | issubset, issuperset, isdisjoint, in | Compare membership structure |
frozenset
frozensetis an immutable set — hashable, so it can be a dict key or element of another set.- No
add/remove; build withfrozenset(iterable). - Supports the same non-mutating algebra:
|,&,-,^, subset tests. - Use when you need a fixed set of tags as a key.
fs = frozenset([1, 2, 2, 3])
print(sorted(fs), type(fs).__name__)
# Output:
# [1, 2, 3] frozenset Set comprehensions
- Syntax:
{expr for x in iterable if cond}— like list comprehensions but builds a set. - Duplicates from
exprcollapse automatically. - Empty
{}is a dict; empty set comprehension still needsset()if you start empty. - Good for filtering uniques in one expression.
nums = [1, 2, 2, 3, 4, 4]
squares = {n * n for n in nums if n % 2 == 0}
print(sorted(squares))
# Output:
# [4, 16] Advanced — Sets
In-place updates
|=,&=,-=,^=update a set in place (alsoupdate,intersection_update, …).- In-place methods often return
None— do not chain them as expressions. - Prefer operators for clarity when both operands are sets.
- Methods accept any iterable; operators require sets (or frozensets) on both sides for
|&etc.
a = {1, 2, 3}
a &= {2, 3, 4}
print(sorted(a))
# Output:
# [2, 3] Hashability rules
- Mutable sets are not hashable — cannot nest a bare
setinside a set. - Nest with
frozenset:{frozenset({1, 2}), frozenset({3})}. - Custom classes need
__hash__and__eq__consistency to live in sets. - Never mutate an object after inserting it into a set/dict key.
When sets beat lists
- Repeated
inchecks on large collections: set is ~O(1) vs list O(n). - Natural model for “unique tags”, “seen ids”, graph adjacency as sets of neighbors.
- Not for ordered data, duplicates-with-multiplicity, or index access.
- Sorting a set for display does not make the set ordered afterward.
Interview patterns
- Two-sum / pair existence often uses a seen set.
- Anagram check: compare character Counter — or sorted strings; sets alone lose counts.
- Find missing numbers: set difference against an expected range.
- Remove duplicates from a stream with a seen set while building a result list.
Tricky Interview Points
Q1) How do you create an empty set?
Answer Call set(). {} creates an empty dictionary, not a set.
Q2) Are sets ordered?
Answer Do not rely on order for output or indexing. For stable display, use sorted(s). (Implementation details changed over versions; interviews want “unordered / unique”.)
Q3) remove vs discard?
Answer remove raises KeyError if the element is absent; discard does nothing.
Q4) What types can a set contain?
Answer Hashable types only: numbers, strings, tuples of hashables, frozensets — not lists, dicts, or sets.
Q5) What is a frozenset?
Answer An immutable set. It is hashable and can be used as a dict key or as an element inside another set.
Q6) Union vs intersection vs difference?
Answer Union = either set; intersection = both; difference = in first but not second. Symmetric difference = in exactly one.
Q7) Why use a set for membership tests?
Answer Average O(1) lookups via hashing, much faster than scanning a list for large n.
Q8) Does set([1, 2, 2]) keep duplicates?
Answer No. The result is {1, 2} — uniqueness is enforced.
Q9) Can you index a set with s[0]?
Answer No. Sets do not support indexing. Iterate or convert to a sorted list.
Q10) How do you nest sets?
Answer Use frozenset elements, because a plain set is unhashable.
Q11) What does isdisjoint mean?
Answer Two sets are disjoint when their intersection is empty — no shared elements.
Q12) Operator | vs method union?
Answer Both compute union. union accepts any iterable; | expects set-like operands.
Simple Programs
Unique elements
data = [3, 1, 2, 3, 1]
print(sorted(set(data)))
# Output:
# [1, 2, 3] Union and intersection
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(sorted(a | b))
print(sorted(a & b))
# Output:
# [1, 2, 3, 4, 5]
# [3, 4] Students in only one course
math = {"Ann", "Bob", "Cara"}
physics = {"Bob", "Dan"}
only_one = math ^ physics
print(sorted(only_one))
# Output:
# ['Ann', 'Cara', 'Dan'] Seen set — first duplicates
nums = [1, 2, 3, 2, 4, 1]
seen = set()
dups = set()
for n in nums:
if n in seen:
dups.add(n)
else:
seen.add(n)
print(sorted(dups))
# Output:
# [1, 2] Missing numbers via difference
have = {1, 3, 5}
need = set(range(1, 6))
print(sorted(need - have))
# Output:
# [2, 4] frozenset as dict key
groups = {
frozenset(["a", "b"]): "ab-team",
frozenset(["c"]): "solo",
}
key = frozenset(["b", "a"])
print(groups[key])
print(groups[frozenset(["c"])])
# Output:
# ab-team
# solo Problem Solving Tricks
- Write
set()for empty sets —{}is a dict. - Always
print(sorted(s))in examples so output is deterministic. discardwhen absence is normal;removewhen absence is a bug.- Use sets for fast
inchecks on large collections. - Order-preserving dedupe:
list(dict.fromkeys(xs)), notlist(set(xs)). - Nest sets via
frozensetonly. - Remember
| & - ^and the in-place|= &= -= ^=forms. - Sets need hashable elements — convert lists to tuples first if needed.
isdisjointis clearer thannot (a & b)for intent.- Do not use sets when duplicates or positions matter.
Practice Programs List
- Build a set from a list with duplicates and print
sorted(...). - Demonstrate that
{}is a dict andset()is a set. - Compute union, intersection, difference, and symmetric difference for two sets.
- Show
removeraising vsdiscardstaying quiet. - Find common students across three course sets.
- Detect duplicates in a list using a seen set.
- Find missing integers from 1..N with set difference.
- Use a set comprehension to collect unique word lengths.
- Store frozenset keys in a dict and look up with a differently ordered frozenset.
- Explain with code why
[1, 2]cannot be added to a set but(1, 2)can. - Update a set in place with
&=and print the sorted result. - Compare timing mentally: 10_000
inchecks on list vs set — when would you switch?