Lesson · Core Collections
Collection Semantics & Complexity
63 min readCollection Semantics & Complexity
Choosing a collection is a design decision, not just a syntax decision. This lesson compares mutability, ordering, hashability, and common operation costs so you can select the right structure.
Learning goals
- Classify a built-in collection as a sequence, mapping, or set and name the contract each one satisfies.
- Explain what mutability changes about sharing, aliasing, and which objects can be dict keys.
- Say when iteration order is guaranteed and when treating it as meaningful is a bug.
- Compare the cost of membership, append, and lookup across list, dict, set, and deque in plain words.
- Choose a structure from an operation profile instead of reaching for a list by habit.
Mental model
The choices form a stack of questions: the meaning of one element picks the family, mutability decides what can be shared or hashed, the ordering guarantee decides whether iteration order may be relied on, and the operation profile decides what the structure costs as it grows. Each question narrows the options, and the structure that survives all four is the one whose contract makes the hottest operation cheap and readable.
Four questions pick the structure
the survivor makes the hottest operation cheap
Mental model
the same mechanism as a compact list
what does one element mean? position → sequence, label → mapping, uniqueness → set ↓ will the container change? mutable (list, dict, set, deque) vs immutable (tuple, frozenset) ↓ does order carry meaning? guaranteed (list, tuple, dict) vs unordered (set) ↓ what runs hottest? one hash probe (dict/set) vs a scan (list) or a shift (front pops)
Core idea
Collection types are contracts: a sequence answers by position, a mapping by key, and a set by membership and uniqueness, and the operations that feel natural follow from that contract. Two questions then decide the practical differences, whether the object is mutable and whether its order is guaranteed, and the operation profile decides the cost: the same membership test is a single hash probe in a dict or set and a front-to-back scan in a list. Choosing well means reading what the program does to its data most often and picking the structure whose contract makes that operation cheap and obvious.
Sequence vs mapping vs set
This comparison separates Sequence from mapping vs set in the context of Collection Semantics & Complexity. Focus on ownership, mutability, cost, failure behavior, and API intent rather than treating the two choices as interchangeable.
Mutable vs immutable
This comparison separates Mutable from immutable in the context of Collection Semantics & Complexity. Focus on ownership, mutability, cost, failure behavior, and API intent rather than treating the two choices as interchangeable.
Ordered behavior
Ordering semantics answer whether iteration order is meaningful and guaranteed. Lists, tuples, and modern dictionaries preserve order; sets intentionally do not provide sequence-style positional order.
Hashable vs unhashable
This comparison separates Hashable from unhashable in the context of Collection Semantics & Complexity. Focus on ownership, mutability, cost, failure behavior, and API intent rather than treating the two choices as interchangeable.
Membership complexity
Membership complexity connects Python syntax to algorithmic behavior. Focus on growth with input size, expected versus worst-case behavior, and whether hidden copying or shifting occurs.
Append complexity
Append complexity connects Python syntax to algorithmic behavior. Focus on growth with input size, expected versus worst-case behavior, and whether hidden copying or shifting occurs.
Dictionary/set expected lookup cost
Dictionary/set expected lookup cost connects Python syntax to algorithmic behavior. Focus on growth with input size, expected versus worst-case behavior, and whether hidden copying or shifting occurs.
Choosing the right collection
Choosing the right collection means matching a structure's contract to what the program does most often with its data. Name what one element means (position, key, or just membership), the cost of the hot operations, and whether mutability or ordering guarantees are required, then pick the simplest type that satisfies all three. A list or dict is the usual starting point; move to a set, deque, tuple, or frozenset when a concrete requirement justifies it.
Walkthrough
- The four assignments show the contracts side by side:
numbersis a sequence that answers by position,lookupmaps the label"a"to1, anduniquestores only values, so it can never hold duplicates. print(2 in numbers, "a" in lookup, 2 in unique)runs one operator against three structures; all three answerTruehere, but the dict and set answer with a hash probe while the list scans.deque([1, 2, 3])is a sequence too, yet itspopleft()removes the left end cheaply, where removing the front ofnumberswould shift every remaining element.- Predict before running: the three booleans, and what
queuecontains after thepopleft()call returns1.
Experiments to try
- Try
tuple_side = (1, 2); tuple_side.append(3)and read theAttributeError; it reports that the tuple has no mutating API at all, not that an import is missing. - Time
-1 in list(range(10000))against-1 in set(range(10000))and connect the gap to scanner versus hash probe. - Build
{[1, 2]}and then{(1, 2)}; only the tuple enters a set, because a set member must be hashable. - Run
queue.appendleft(0)and compare it withnumbers.insert(0, 0); note which structure offers a cheap operation at the end you are touching.
Playable lesson
Lab: Collection choice lab
Give an operation profile such as frequent membership tests or left-side queue operations and let the learner compare list, set, dict, tuple, and deque.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
Collection choice lab
answer to reveal the cost of each structure| structure | contract | cost for this workload |
|---|---|---|
| list | ordered, mutable sequence | answer to reveal |
| set | unique, unordered, hashable members | answer to reveal |
| dict | ordered mapping key to value | answer to reveal |
| tuple | ordered, immutable sequence | answer to reveal |
| deque | double-ended sequence, cheap at both ends | answer to reveal |
Predict first
Why is membership flat in a set but growing in a list?
The moment a membership test runs in a loop over a large list, the scan becomes the program's cost.
The trap is reaching for a list by default: it is the right contract for position, not for membership.
Common mistakes
- Defaulting to a list for repeated membership tests:
x in numbersscans from the front until it finds a match, while a set or dict answers with one hash probe regardless of size. - Removing from the front of a list in a loop: every
pop(0)orinsert(0, ...)shifts the remaining elements, so usedequewhen both ends are active. - Treating set iteration order as meaningful: it follows hash table internals and can look arbitrary, especially for strings; a list or dict is the tool when order is data.
- Putting a mutable value into a set or dict key: code like
{[1, 2]: "x"}raisesTypeError: unhashable type, because mutating a key would make it unreachable in the table.
Practice: Easy
- Run the worked example's membership line and label which of the three contracts (position, key, uniqueness) each structure satisfies.
- Print
numbers,lookup, andunique; write one sentence for each about what a position, a key, and uniqueness mean for that object. - Trigger two failures:
(1, 2).append(3)andunique.add([1]); record the exception types and connect each to mutability or hashability.
Practice: Medium
- Take a 10,000-element list and a set of the same values, measure a missing-value membership test on both, and explain the result with scan versus hash probe.
- Model a first-in-first-out queue three ways:
list.pop(0), a list used withpop(), anddeque.popleft(); argue from cost and readability which one belongs in a job queue. - Build a frequency count in a dict and a separate
seenset from the same text; state which question each answers and why neither replaces the other.
Practice: Hard
- Design a pipeline that deduplicates, counts, and tests membership over a list of tokens; pick a structure for each stage, justify it with the operation profile, and define the input and one test before implementing.
- Build a failure lab with three cases: front removal in a loop, unordered set iteration printed as if it were ordered, and a mutable value used as a key; explain the mechanism behind each result.
- Connect this lesson to the sorting lesson: explain how moving access patterns from a list into a dict or set changes what the rest of the program has to do, and describe when keeping both a set and a list is worth the duplication.
Lesson checklist
- I can name the contract a built-in collection satisfies: position, key, or uniqueness.
- I can say what mutability and hashability allow, and where a
frozensetor tuple fits in. - I can predict which operations stay cheap as data grows and which pay a scan or a shift.
- I can justify a structure from an operation profile instead of defaulting to a list.
Remember
Collection choice follows the contracts and the hot path: sequences answer by position, mappings by key, and sets by uniqueness, while mutability and ordering promises decide what may be shared, hashed, and relied on for output. The same membership test costs one hash probe in a dict or set and a full scan in a list, so picking the structure that matches the frequent operation is what keeps a program fast as its data grows.
Interview angles
What is the main purpose of **Sequence vs mapping vs set**?+
This comparison separates Sequence from mapping vs set in the context of Collection Semantics & Complexity. Focus on ownership, mutability, cost, failure behavior, and API intent rather than treating the two choices as interchangeable.
What should you pay attention to when using **Mutable vs immutable**?+
This comparison separates Mutable from immutable in the context of Collection Semantics & Complexity. Focus on ownership, mutability, cost, failure behavior, and API intent rather than treating the two choices as interchangeable.
How does **Ordered behavior** fit into this lesson?+
Ordering semantics answer whether iteration order is meaningful and guaranteed. Lists, tuples, and modern dictionaries preserve order; sets intentionally do not provide sequence-style positional order.
Why does `x in some_list` get slower as the list grows while `x in some_set` stays roughly flat?+
The list scan compares x against elements from the front until it finds a match, so the work grows with the number of elements; the set computes the hash once and probes the table, which stays roughly constant as the set grows.