Sub topic 10
A decision guide for choosing a collection
You now know how lists, tuples, dictionaries, and sets behave one at a time. This chapter turns that knowledge into a repeatable way to choose between them. It assumes you have read the earlier chapters on mutability, hashability, and lookup cost, and that you can write loops and functions in Python 3.
The goal is a short list of questions you can ask about any piece of data. The answers point to a collection type, and in most cases they point to exactly one.
Start from what the code must do
Choose a collection by the operations your code performs most often, not by habit. The table maps common needs to the type that serves them best.
| What you need | Best fit | Reason |
|---|---|---|
| Items in a defined order, which will grow or shrink | `list` | Ordered, indexable, mutable |
| A fixed group of values that belong together | `tuple` | Ordered, indexable, immutable, hashable if its items are |
| Find a value from a label, ID, or other key | `dict` | Average constant-time lookup by key |
| Ask "have I seen this?" many times | `set` | Average constant-time membership test |
| Remove duplicates, order does not matter | `set` | Stores each element once |
| Remove duplicates, keep first-seen order | `dict.fromkeys` | Dict keys are unique and keep insertion order |
| Combine or compare groups (shared, missing, extra) | `set` | Union, intersection, and difference operators |
| A composite value used as a dict key or set element | `tuple` or `frozenset` | Both are hashable when their contents are |
Most real programs need more than one of these. A common pattern is a dict whose values are lists or sets.
A decision flow
The diagram below puts the questions in the order that usually settles the choice fastest. Key lookup and uniqueness are asked first because they are the most specific needs. Order and mutability are the fallback.
The flow is a default, not a law. If the answers conflict, for example you need uniqueness and order, combine types rather than forcing one to do both jobs.
Question 1: do you look things up by a key?
If you often write "find the item whose ID is X" or "what is the value for this name", use a dict. A list forces a scan of every item. A dict goes straight to the item.
A common mistake is keeping records in a list and searching it each time:
users = [{"id": 1, "name": "Ana"}, {"id": 2, "name": "Ben"}]
# Scans the list on every call
def find_slow(user_id):
for u in users:
if u["id"] == user_id:
return u
return None
# Build the index once, then each lookup is a single step
by_id = {u["id"]: u for u in users}
print(by_id[2]["name"]) # Ben
print(by_id.get(99, "unknown")) # unknownBuilding by_id costs one pass over the list. It pays off as soon as you do more than a few lookups. If the list changes later, the dict does not update itself. You must update both, or rebuild the index.
Use dict.get(key, default) when a missing key is a normal case. Use d[key] when a missing key is a bug and you want a KeyError to say so.
Question 2: is uniqueness or membership the main job?
Use a set when the question is "is this in the group?" or "which items are in both groups?". A set stores no duplicates and answers membership in constant time on average.
A set is also the right choice when you only need keys. A dict with throwaway values such as {name: True} is a set written the hard way.
allowed = {"ana", "ben", "cy"}
requests = ["ana", "dee", "ben", "eli"]
denied = [name for name in requests if name not in allowed]
print(denied) # ['dee', 'eli']
a = {"python", "sql", "go"}
b = {"sql", "rust", "go"}
print(sorted(a & b)) # ['go', 'sql'] skills both people have
print(sorted(a - b)) # ['python'] skills only the first hasTwo limits matter in practice:
- A set has no useful order. Do not depend on the order in which it prints or iterates. Wrap it in
sorted(...)when order matters for output or tests. - Elements must be hashable. You cannot put a list or another set inside a set. Convert lists to tuples first, or use
frozensetfor inner sets.
If you need to remove duplicates and keep order, a set alone is not enough:
items = ["b", "a", "b", "c", "a"]
print(list(dict.fromkeys(items))) # ['b', 'a', 'c']Question 3: does position or order matter?
If you do not need key lookup or uniqueness, you are choosing between a list and a tuple. Both are ordered and support indexing and slicing. The difference is intent.
| Property | `list` | `tuple` |
|---|---|---|
| Can grow, shrink, or change items | Yes | No |
| Typical contents | Many items of the same kind | A few items with different roles |
| Hashable | Never | Only if all items are hashable |
| Typical use | Collected results, queues, rows | Coordinates, return values, composite keys |
Pick a list when the number of items is not known in advance, or when items are added, removed, or sorted in place. Pick a tuple when the shape is fixed and each position has its own meaning, such as (latitude, longitude) or (name, age, city).
A tuple also tells readers that nobody should change this value. That is useful in function return values and constants:
def min_max(values):
return min(values), max(values)
low, high = min_max([4, 9, 2, 7])
print(low, high) # 2 9Immutability is shallow. A tuple holding a list can still have that list changed, and the tuple is then unhashable. Do not use a tuple of mutable objects when you need something truly constant.
Question 4: must the value be hashable or fixed?
This question applies when the data will itself be used as a dict key or a set element. Lists and sets cannot be keys. Tuples and frozensets can, as long as everything inside them is hashable.
Use a tuple when the key has several ordered parts:
visited = {(0, 0), (0, 1)}
def step(pos, dx, dy):
return (pos[0] + dx, pos[1] + dy)
pos = step((0, 0), 0, 1)
print(pos in visited) # TrueUse a frozenset when the key is a group whose order must not matter:
distance = {frozenset({"Oslo", "Bergen"}): 463}
print(distance[frozenset({"Bergen", "Oslo"})]) # 463With a tuple, ("Oslo", "Bergen") and ("Bergen", "Oslo") are two different keys. With a frozenset they are the same key.
Using several collections together
Real data is rarely one flat group. The right answer is often a dict whose values are lists or sets. The choice of inner type follows the same questions as before.
def tag_index(posts):
index = {}
for post_id, tags in posts:
for tag in tags:
index.setdefault(tag, set()).add(post_id)
return index
posts = [(1, ["python", "dicts"]), (2, ["python", "sets"]), (3, ["sets"])]
index = tag_index(posts)
print(sorted(index["python"])) # [1, 2]
print(sorted(index["sets"] & index["python"])) # [2]Each post is a tuple, because it is a fixed pair of an ID and its tags. The index is a dict, because you look posts up by tag. Each value is a set, because a post should appear once per tag and you want to intersect results. Replacing the inner set with a list would still run, but posts could be listed twice and the intersection would need extra code.
Cost as a tiebreaker
When two types fit, let cost decide. The figures below are typical costs for a collection of n items.
| Operation | `list` | `tuple` | `dict` | `set` |
|---|---|---|---|---|
| Get by index | O(1) | O(1) | not applicable | not applicable |
| Get by key | not applicable | not applicable | O(1) average | not applicable |
| `x in collection` | O(n) | O(n) | O(1) average (keys) | O(1) average |
| Add at the end | O(1) amortized | not possible | O(1) average | O(1) average |
| Insert or delete at the front | O(n) | not possible | not applicable | not applicable |
The difference shows up quickly when a membership test sits inside a loop. You can measure it yourself:
import timeit
n = 100_000
as_list = list(range(n))
as_set = set(as_list)
missing = -1 # worst case for the list: it must scan everything
print("list:", timeit.timeit(lambda: missing in as_list, number=100))
print("set: ", timeit.timeit(lambda: missing in as_set, number=100))The exact numbers depend on your machine. The set time will be many times smaller. Hash-based types also use more memory than a list of the same items, so for a few dozen items the cost difference rarely matters. Pick the type that states your intent most clearly.
Frequent wrong choices
These mistakes appear often in code reviews. Each has a quick fix.
- A list used for membership in a loop.
if x in big_listinside a loop makes the work grow with both sizes. Convert the list to a set once, before the loop. - A dict with dummy values.
{name: None}or{name: True}only records presence. Use a set. - A list of records searched by field. Build a dict keyed by that field, as in the
by_idexample. - A tuple chosen, then appended to. If you keep rebuilding a tuple with
t = t + (x,), you want a list. Each concatenation copies the whole tuple. - A set chosen for display order. Sets do not promise a useful order. Use a list, or
sorted(some_set). - A list used as a dict key. This raises
TypeError: unhashable type: 'list'. Convert it withtuple(my_list)if the items are hashable. - A set used where duplicates carry meaning. If you need to know how many times something appeared, a set throws that away. Count instead (see the next section).
Knowing when the basics are not enough
The four built-ins cover most tasks, and the standard library has variants for common patterns. Reach for them when your code starts to repeat the same workaround.
| Pattern in your code | Alternative | Module |
|---|---|---|
| Tuple fields accessed by position, hard to read | `namedtuple` | `collections` |
| Counting how often each item appears | `Counter` | `collections` |
| `if key not in d: d[key] = []` before every append | `defaultdict(list)` | `collections` |
| Frequent removal from the front of a list | `deque` | `collections` |
| A set that must be hashable | `frozenset` | built-in |
Start with the plain type. Switch only when the alternative removes real boilerplate or fixes a real cost problem.
A short checklist
- Do I look values up by a key? Use a dict.
- Do I mostly ask "is it in there?" or need unique items? Use a set.
- Is it a small fixed record, or must it be a key? Use a tuple, or a frozenset for unordered groups.
- Otherwise, is it an ordered group that changes? Use a list.
- Is a nested structure needed? Choose each layer with the same four questions.
- Is the same workaround repeated? Check the standard library alternatives.
Exercise
You have a list of 50,000 email addresses and a loop that checks for each incoming address whether it is already in the list. What collection should the addresses be stored in, and why? What would you change if you also needed to know the sign-up date for each address?
Show answer
Store them in a set, because in on a set takes constant time on average, while in on a list scans up to 50,000 items on every check. If you also need the sign-up date, use a dict that maps each email address to its date, such as {"[email protected]": date}. The dict keeps the fast membership test (email in signups) and lets you read the date by key.
Exercise
You need to store the distance between pairs of cities, and ("Oslo", "Bergen") must give the same answer as ("Bergen", "Oslo"). Write the key you would use for the pair Oslo and Bergen, and explain why a plain tuple key is a poor choice.
Show answer
Use frozenset({"Oslo", "Bergen"}) as the key. A frozenset is hashable and ignores order, so frozenset({"Bergen", "Oslo"}) finds the same entry. A plain tuple key is order-sensitive, so ("Oslo", "Bergen") and ("Bergen", "Oslo") would be two different keys, and you would have to store the distance twice or sort the pair every time.
Exercise
A function must return the three values name, age, and city for one person, and callers should not be able to modify the result. Which type fits best, and what is one thing to watch for if city were a list?
Show answer
A tuple fits best: the shape is fixed, each position has its own meaning, and the result cannot be changed by index assignment. If city were a list, the tuple would be only shallowly immutable. Callers could still change that inner list, and the tuple would no longer be hashable, so it could not be used as a dict key or set element.