Lite / Intelligent Robotic Systems / Week 4
List, tuple, set or dict? Pick the right container
Checking whether a part number is in a list of 100,000 parts takes up to 100,000 comparisons. With a set it takes about one. What changed?
Why should I care?
The container you choose decides how fast your program can answer its most common question. Pick a list when order matters, a set when you ask 'have I seen this?', a dict when you ask 'what is the value for this key?', and a tuple for a small fixed record like a cell (row, col).
- Choose between list, tuple, set and dict for a task and justify the choice.
- Explain why membership tests and lookups by key are fast in sets and dicts but slow in lists.
- Use tuples for fixed records such as grid cells and as dictionary keys.
Predict
A route planner must check 'have I already visited this cell?' thousands of times. Which container should hold the visited cells?
- A list
- A set of (row, col) tuples
- A string
- A list of lists
Guess first, then reveal
A set of tuples. A set finds an item by hashing it, so 'cell in visited' takes about the same time however many cells are stored. With a list it scans from the start, getting slower as the search grows.
Discover
Open Dict (inventory) mode and look up each part. Note how many names a list scan would have to compare. Look up the part that isn't stocked: what happens with [] and with .get()? Then switch to List mode and compare.
What the interactive shows (text version)
The dict mode shows an inventory of six parts. Looking up 'servo SG90' returns 6 directly; as a list of pairs a scan would compare 4 names. Looking up an unstocked 'M4 bolt' raises KeyError with square brackets but returns 0 with .get(key, 0); a list scan would check all 6 names.
Watch (optional)
Watch for: Watch for how an array, a linked list and a hash table are laid out, and which questions each answers quickly.
A fast tour of arrays, strings, stacks, queues, trees and graphs, and how each is laid out in memory.
“Data Structures: Crash Course Computer Science #14” by CrashCourse (opens YouTube; streaming video uses a lot of data)
The video is optional. Everything you need is in this lesson's text.
Understand
Four containers, four questions
list: ordered, indexable, may repeat; 'what is the 5th reading?'. tuple: like a list but fixed, perfect for a record such as (row, col). set: unordered, no repeats; 'is this in the collection?'. dict: keys mapped to values; 'what is the stock of this part?'.
Why sets and dicts are fast
A set or dict computes a hash of the key, which says roughly where to look, so x in s and d[k] take about the same time whether there are 10 items or 10 million (on average). x in some_list compares items one by one: up to n comparisons.
Keys must not change
Only immutable values can be set members or dict keys: numbers, strings and tuples of them. That is another reason to store a cell as the tuple (3, 7) rather than the list [3, 7]. Lists can't be hashed, so {[3, 7]} raises TypeError.
Explain it another way
Intuitive
A list is a queue of people you check one by one; a dict is a cloakroom where your ticket number takes you straight to your coat.
Technical
Average costs: list index O(1), list membership O(n), append O(1) amortised, insert at the front O(n); set/dict membership, insert and lookup O(1) on average. The price is memory and no ordering by value (dicts do keep insertion order in Python 3.7+).
Applied
Path planners keep the visited set as a hash set of cell tuples and the best-known cost per cell as a dict; switching a visited list to a set is often the single biggest speed-up in a student planner.
Worked example 1
Store visited cells and per-cell costs for a planner.
visited = set()
cost = {}
start = (3, 0)
visited.add(start)
cost[start] = 0
for cell, c in [((3, 1), 1), ((2, 0), 1), ((3, 1), 1)]:
if cell not in visited: # average O(1), however big visited gets
visited.add(cell)
cost[cell] = c
print(len(visited), cost[(2, 0)], (9, 9) in visited) # 3 1 False
print(cost.get((9, 9), "unreached")) # unreachedCommon mix-ups
Sets are just lists without duplicates.
✓ Sets are hash tables: unordered, with fast membership tests. That speed is the main reason to use one.Dicts are slow because they are complicated.
✓ Average dict lookup is about as fast as list indexing and far faster than searching a list.
Practice
Practice, not a test. Answers are checked on our server; a wrong answer gets a hint and another try. Nothing is saved.
Apply it
Rewrite a planner's visited list as a set and its distance list as a dict keyed by cell tuples. On a 100 × 100 open grid, count how many membership comparisons the list version would make in total (sum the list length at each check) and compare with one lookup per check for the set.
Reflect
Which question does your current project ask most often, and which container answers it fastest?
Write your answer on paper or in your own notes. Lite never stores what you write.
Go further
- Python docs: data structures
Lists, tuples, sets and dictionaries side by side, with examples.