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?
About 35 min · 3 goals · Checked by automated tests
1.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.
2.Watch
→ 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.
Length: see YouTube · captions on YouTube · source
Nothing loads from YouTube until you press play.
The video is optional: everything you need is also in the lesson text and the interactive.
3.Predict
A route planner must check 'have I already visited this cell?' thousands of times. Which container should hold the visited cells?
Guess first. Being wrong here is how the surprise works.
4.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.
Loading the interactive…
Can't use the interactive? Read a description instead
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.
5.Checkpoint: guided practice
Check what you just discovered before going on. Hints appear after a wrong answer.
Practice 1
You need the stock quantity for any part number, looked up thousands of times. Which container?
Practice 2
visited = set(); visited.add([3, 7]). What happens?
6.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
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.
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+).
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.
7.Practice on your own
Practice, not a test. Wrong answers get a hint and another try.
Practice 3
A list holds 50,000 part numbers in random order. Checking a part that is NOT in the list: how many comparisons does 'p in parts' make?
Practice 4
A planned path must keep its waypoints in order and may visit the same waypoint twice. Which container?
Practice 5
stock = {'M3-BOLT': 120}. What does stock.get('M4-BOLT', 0) return?
8.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.
9.Reflect
10.Go further
- Python docs: data structures ↗Lists, tuples, sets and dictionaries side by side, with examples.
Concepts: Lists, dictionaries and tabular data · Algorithms, searching and complexity