PART 1 · PYTHON FROM ZERO · LESSON 13
Which data structure? A side-by-side guide
FreeLesson 15 of 78
Choosing the right container is half of every coding question. Here are all four side by side, with the question to ask yourself.
| list | tuple | set | dict |
|---|---|---|---|
Looks like [1, 2, 2] | (1, 2) | {1, 2} | {"a": 1} |
| Ordered Yes | Yes | No | Yes (insertion order) |
| Changeable Yes | No | Yes | Yes |
| Duplicates Yes | Yes | No | Keys unique, values can repeat |
| Find an item Slow: checks one by one | Slow | Fast | Fast, by key |
| Ask yourself "Do I need order or positions?" | "Is it a fixed record?" | "Do I only care if it exists?" | "Do I look things up by a name or id?" |
| Rows of a file, daily totals in Real example date order | A (date, amount) pair | IDs already loaded | customer_id to customer record |
import time
ids_list = list(range(1_000_000))
ids_set = set(ids_list)
start = time.perf_counter()
print(999_999 in ids_list) # checks a million items
list_ms = (time.perf_counter() - start) * 1000
start = time.perf_counter()
print(999_999 in ids_set) # jumps straight to it
set_ms = (time.perf_counter() - start) * 1000
print(f"list {list_ms:.2f} ms vs set {set_ms:.4f} ms")Output
True True list 10.66 ms vs set 0.0049 ms
The times are what this run measured when the book was built. Yours will differ.
names = ["Aarav", "Diya", "Aarav", "Kabir"]
print(list(set(names))) # dedupe (order lost)
print(list(dict.fromkeys(names))) # dedupe, order kept
ids = [101, 102, 103]
amounts = [1198, 796, 1499]
print(dict(zip(ids, amounts))) # two lists -> one dict
print(sorted({"b": 2, "a": 1}.items())) # dict -> sorted pairs
print(tuple(ids), set("banana"))Output
['Diya', 'Kabir', 'Aarav']
['Aarav', 'Diya', 'Kabir']
{101: 1198, 102: 796, 103: 1499}
[('a', 1), ('b', 2)]
(101, 102, 103) {'a', 'n', 'b'}zip pairs items from two lists by position. dict.fromkeys keeps the first time each name appears, so it removes duplicates without shuffling the order.
Quick check: which would you use?
| Task | Pick | Because |
|---|---|---|
| Store the 15 orders in the order they happened | list | Order matters |
| Remember which customer ids you have already loaded | set | Only "seen or not", fast |
| Look up a product's price by its name | dict | Lookup by key |
| Return a (min, max) pair from a function | tuple | Fixed record |
| Count orders per status | dict | status -> count |
Practice before you move on
- Load the customer_id values of orders.csv into a list, a set and a Counter, and use each one to answer: has customer 3 ordered?
- Change the million ids example to look for an id that is not there, and compare the list and set timings again.