Skip to main content

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.

L1

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} or set(iterable). Empty set must be set() — {} 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} is True.
  • There is no indexing: s[0] raises TypeError.
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), not s.len().
  • For stable demo/output order, wrap with sorted(s) — sets are unordered for teaching purposes.
FunctionWhat it doesExampleResult
len(s)Number of unique elementslen({1, 2, 2, 3})3
set(iterable)Build a set (drops duplicates)set([1, 2, 2, 3]){1, 2, 3}
frozenset(iterable)Immutable setfrozenset([1, 2])frozenset({1, 2})
sorted(s)Sorted **list** of elementssorted({"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 elementmin({3, 1, 2})1
sum(s)Sum of numberssum({1, 2, 3})6
any(s) / all(s)Truthy checksall({1, 2, 3})True
isinstance(s, set)Type checkisinstance({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) raises KeyError if 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).
MethodWhat it doesExampleNotes
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 copyt = 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 | b or a.union(b) — elements in either.
  • Intersection: a & b or a.intersection(b) — elements in both.
  • Difference: a - b or a.difference(b) — in a but not b.
  • Symmetric difference: a ^ b — in one set but not both.
OperationOperatorMethodExample result
Uniona | ba.union(b){1,2,3} | {3,4} → {1,2,3,4}
Intersectiona & ba.intersection(b){1,2,3} & {3,4} → {3}
Differencea - ba.difference(b){1,2,3} - {3,4} → {1,2}
Sym. differencea ^ ba.symmetric_difference(b){1,2,3} ^ {3,4} → {1,2,4}
In-place uniona |= ba.update(b)Mutates a
In-place intersectiona &= ba.intersection_update(b)Mutates a
In-place differencea -= ba.difference_update(b)Mutates a
In-place sym. diffa ^= ba.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 of a is in b.
  • a >= b / a.issuperset(b) — a contains every element of b.
  • a.isdisjoint(b) — no common elements.
  • Proper subset uses < (subset and not equal).
TestOperatorMethodMeaning
Subseta <= ba.issubset(b)Every element of a is in b
Proper subseta < b—Subset and not equal
Superseta >= ba.issuperset(b)a contains every element of b
Proper superseta > b—Superset and not equal
Disjoint—a.isdisjoint(b)No common elements
Membershipx 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 s is average O(1) — the main reason to use sets.
  • Deduplicate a list: list(set(a)) loses order; use list(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.
NeedPrefer
Fast membershipx 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 keyfrozenset(items)

set APIs — overview cheat sheet

  • Use sets for uniqueness and fast in checks; use lists when order or duplicates matter.
CategoryCommon APIsUse when
Built-inslen, set, frozenset, sorted, min, max, sumCreate, measure, display
Mutateadd, update, remove, discard, pop, clearGrow or shrink a set
Algebra| & - ^, union, intersection, …Combine sets mathematically
Relationsissubset, issuperset, isdisjoint, inCompare membership structure

frozenset

  • frozenset is an immutable set — hashable, so it can be a dict key or element of another set.
  • No add/remove; build with frozenset(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 expr collapse automatically.
  • Empty {} is a dict; empty set comprehension still needs set() 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]
L2

Advanced — Sets

In-place updates

  • |=, &=, -=, ^= update a set in place (also update, 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 set inside 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 in checks 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.
L3

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.

L4

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
L5

Problem Solving Tricks

  • Write set() for empty sets — {} is a dict.
  • Always print(sorted(s)) in examples so output is deterministic.
  • discard when absence is normal; remove when absence is a bug.
  • Use sets for fast in checks on large collections.
  • Order-preserving dedupe: list(dict.fromkeys(xs)), not list(set(xs)).
  • Nest sets via frozenset only.
  • Remember | & - ^ and the in-place |= &= -= ^= forms.
  • Sets need hashable elements — convert lists to tuples first if needed.
  • isdisjoint is clearer than not (a & b) for intent.
  • Do not use sets when duplicates or positions matter.
L6

Practice Programs List

  1. Build a set from a list with duplicates and print sorted(...).
  2. Demonstrate that {} is a dict and set() is a set.
  3. Compute union, intersection, difference, and symmetric difference for two sets.
  4. Show remove raising vs discard staying quiet.
  5. Find common students across three course sets.
  6. Detect duplicates in a list using a seen set.
  7. Find missing integers from 1..N with set difference.
  8. Use a set comprehension to collect unique word lengths.
  9. Store frozenset keys in a dict and look up with a differently ordered frozenset.
  10. Explain with code why [1, 2] cannot be added to a set but (1, 2) can.
  11. Update a set in place with &= and print the sorted result.
  12. Compare timing mentally: 10_000 in checks on list vs set — when would you switch?