Cohort 4Register

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.

listtuplesetdict
Looks like [1, 2, 2](1, 2){1, 2}{"a": 1}
Ordered YesYesNoYes (insertion order)
Changeable YesNoYesYes
Duplicates YesYesNoKeys unique, values can repeat
Find an item Slow: checks one by oneSlowFastFast, 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 orderA (date, amount) pairIDs already loadedcustomer_id to customer record
WHY THE CHOICE MATTERS: FINDING ONE ID IN A MILLIONPYTHON 3.12
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.

CONVERTING BETWEEN THEMPYTHON 3.12
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?

TaskPickBecause
Store the 15 orders in the order they happenedlistOrder matters
Remember which customer ids you have already loadedsetOnly "seen or not", fast
Look up a product's price by its namedictLookup by key
Return a (min, max) pair from a functiontupleFixed record
Count orders per statusdictstatus -> count

Practice before you move on

  1. 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?
  2. Change the million ids example to look for an id that is not there, and compare the list and set timings again.