Tuples, copies and choosing the right structure
Choosing the right structure
Goal: Select list, tuple, dictionary or set for a given task and explain why · 9 min
Choose the structure that matches what you need to do with the data.
| need | structure | why |
|---|---|---|
| ordered sequence, duplicates allowed, change it | list | indexing, slicing, append, sort |
| fixed group of values, never changes | tuple | immutable, usable as dictionary key |
| look up a value by name or id | dictionary | fast lookup by key |
| unique items, membership test, set algebra | set | no duplicates, fast "in" |
| ordered unique items | list from sorted(set(...)) or dict keys |
Speed in practice (average case):
x in my_listchecks items one by one: it takes longer the larger the list (O(n)).x in my_setandkey in my_dictuse hashing and stay fast however large the collection (about O(1)).
A task that repeats "is this item in the collection?" thousands of times should use a set or dictionary, not a list.
Combining structures is normal: a list of dictionaries is a table of records ([{"name": "Ada", "age": 36}, …]); a dictionary of lists groups items under a key; a dictionary with tuple keys can index a grid ({(0, 1): "X"}).
Ask three questions: Do I need order? Do I need uniqueness? Do I look things up by key? The answers point to the structure.
Worked example: Which structure for a spell checker?
- We check thousands of words against a dictionary of 100,000 valid words.
- Order does not matter, duplicates are pointless, and the main operation is "is it in there?"
- → a set of valid words; "word in valid" is fast.
valid = {"cat", "dog", "bird"}
text = ["cat", "cta", "dog"]
print([w for w in text if w not in valid])Output:
['cta']