One Value Is Rarely Enough
A dataset is many values: a list of readings, a record of one customer, a lookup from customer ID to plan, the set of regions that appear. Python has four built-in collections for these, and choosing the right one makes the code shorter and the mistakes rarer. This lesson uses each one on a small set of customer records.
Lists
A list holds values in order. You write it in square brackets, and you can change it after creating it:
readings = [21.5, 19.0, 26.2]
readings.append(24.6)
print(readings, len(readings), readings[1:3], 26.2 in readings)
[21.5, 19.0, 26.2, 24.6] 4 [19.0, 26.2] True
Indexing and slicing work as they do for strings. append() adds a value at
the end; in tests whether a value is present. Unlike a string, you can
replace an item in place:
readings = [21.5, 19.0]
readings[0] = 22.0
print(readings, sorted([3, 1, 2]), max(readings), sum(readings))
[22.0, 19.0] [1, 2, 3] 22.0 41.0
sorted() returns a new sorted list and leaves the original alone;
max(), min() and sum() work on any list of numbers. count(value) tells
you how often a value appears. Asking for a position that does not exist
stops the program:
print([1, 2, 3][3])
IndexError: list index out of range
A list of three items has indexes 0, 1 and 2.
Tuples
A tuple is written in round brackets and cannot change after it is created. Use one for a fixed record, such as a plan and a region that belong together:
point = (2, 3)
point[0] = 5
TypeError: 'tuple' object does not support item assignment
You can unpack a tuple into several variables in one line:
plan, region = ("basic", "West") sets plan to "basic" and region to
"West".
Dictionaries
A dictionary maps keys to values. You look values up by key, not by position:
counts = {"basic": 4}
counts["premium"] = 2
counts.update({"basic": 5})
print(counts, list(counts.keys()), "basic" in counts)
{'basic': 5, 'premium': 2} ['basic', 'premium'] True
Assigning to a new key adds it; assigning to an existing key replaces its
value, and update does either for several keys at once. Keys are unique, and a dictionary keeps them in the order they were
added. in tests the keys, not the values. Looking up a missing key with
square brackets stops the program:
print({"a": 1}["b"])
KeyError: 'b'
get(key, default) returns the default instead, which is useful when a
missing key is normal rather than a mistake. Without a default, get()
returns None.
Sets
A set holds distinct values with no order. Duplicates disappear, and membership tests are fast:
regions = {"North", "South", "North"}
print(len(regions))
2
Sets support the operations you know from diagrams of overlapping groups:
a = {"North", "East"}
b = {"North", "West"}
print(sorted(a | b), sorted(a & b), sorted(a - b))
['East', 'North', 'West'] ['North'] ['East']
| is everything in either set, & is what both share and - is what is in
the first but not the second. Because a set has no order, printing one can
show its items in a different order each time you run the program. Wrap it in
sorted() whenever the order matters to you or to a check.
Choosing a Collection
![A table comparing list, tuple, dictionary and set. Written as: [1, 2], (1, 2), {"a": 1} and {1, 2}. Keeps order: yes, yes, yes, no. Can change later: yes, no, yes, yes. Duplicates: allowed, allowed, no duplicate keys, no. Look up by: position, position, key, membership only.](/open-lessons/python-for-ai-ml/assets/collections-compared.png)
Read the table row by row, and ask which property your data needs. Readings in time order need a list. A record whose parts belong together and should not change fits a tuple. Finding a customer's plan from their ID is a dictionary lookup. The distinct regions, or "is this region known?", is a set. Collections can also hold other collections: a dictionary whose values are tuples is a common way to store records by ID.
Exercise: Counts, Distinct Values and a Lookup Table
You will answer questions about eight customer records using each collection.
Starting state: the course environment from the setup lesson, active in your terminal.
-
Create the exercise folder. macOS and Linux:
mkdir -p ~/pyml-practice/label-counts cd ~/pyml-practice/label-countsWindows PowerShell:
mkdir $HOME\pyml-practice\label-counts cd $HOME\pyml-practice\label-counts -
Save this as
records.pyin that folder:"""Count, deduplicate and look up customer records.""" customer_ids = ["C001", "C002", "C003", "C004", "C005", "C006", "C007", "C008"] plans = ["basic", "premium", "basic", "standard", "basic", "standard", "basic", "premium"] regions = ["North", "South", "East", "North", "West", "South", "North", "East"] print("Customers:", len(customer_ids)) print("First three plans:", plans[:3]) print("Last region:", regions[-1]) counts = { "basic": plans.count("basic"), "standard": plans.count("standard"), "premium": plans.count("premium"), } print("Plan counts:", counts) distinct_regions = set(regions) print("Distinct regions:", sorted(distinct_regions)) print("Has a Central region:", "Central" in distinct_regions) customers = { "C001": ("basic", "North"), "C005": ("basic", "West"), "C008": ("premium", "East"), } print("C005:", customers["C005"]) print("C999:", customers.get("C999", "not found")) customers["C009"] = ("standard", "West") plan, region = customers["C009"] print("C009 plan:", plan, "| region:", region) print("Known customers:", len(customers))Do not name the file
collections.py: Python has its own module with that name, and a file of yours with the same name would hide it from other code. -
Predict the plan counts and the number of known customers, then run it:
python records.pyOutput (every value should match):
Customers: 8 First three plans: ['basic', 'premium', 'basic'] Last region: East Plan counts: {'basic': 4, 'standard': 2, 'premium': 2} Distinct regions: ['East', 'North', 'South', 'West'] Has a Central region: False C005: ('basic', 'West') C999: not found C009 plan: standard | region: West Known customers: 4
How the Script Works
The three lists are parallel: position 0 of each describes customer C001,
position 1 describes C002, and so on. plans[:3] slices the first three
plans and regions[-1] takes the last region.
plans.count("basic") counts how often "basic" appears, and the dictionary
stores one count per plan. Writing three count() calls works for three
plans; the next lesson shows how a loop counts any number of labels.
set(regions) removes the duplicates from the eight regions, leaving four,
and sorted() turns the set into a list in alphabetical order so the output
is the same every time. "Central" in distinct_regions is False because no
customer is in that region.
The customers dictionary maps three IDs to (plan, region) tuples.
customers["C005"] finds one directly by key. customers.get("C999", "not found") returns the default because the key is missing; with square
brackets, it would have raised a KeyError. Assigning to customers["C009"]
adds a fourth record, and plan, region = ... unpacks its tuple into two
variables.
If you added "basic" to the end of plans, the count for basic would become
5, but the parallel lists would no longer have the same length, which is
exactly the kind of mismatch a dictionary of records avoids.
Success: every line matches the output above, including the order of the regions.
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
| Distinct regions in a different order | sorted() is missing | Print sorted(distinct_regions), not the set itself |
KeyError: 'C999' | Square brackets used instead of get() | Use customers.get("C999", "not found") |
| A count of 0 for a plan | A spelling or capital-letter difference, such as "Basic" | Strings must match exactly |
ValueError: too many values to unpack | The tuple has more parts than the variables on the left | Match the number of names to the tuple |
Independent task: add a list last_month = ["North", "South", "Central", "North"] to the end of the script. Print, in sorted order, the regions that
appear this month but not last month, and the regions that appeared last
month but not this month. Predict both before you run it.
-
Clean up. macOS and Linux:
cd ~/pyml-practice ls rm -rf label-countsWindows PowerShell:
cd $HOME\pyml-practice ls Remove-Item -Recurse label-countsCheck that
lsshowslabel-countsbefore you remove it. Keep.venv.
Check Your Understanding
Choose a list, a tuple, a dictionary or a set for each, and give a reason:
- Hourly temperature readings for one day, in time order.
- The latitude and longitude of one weather station.
- Each product code's price, looked up when an order arrives.
- The product codes that have been ordered at least once.
Answer and Reasoning
Independent task
Add these lines to the end of the script:
last_month = ["North", "South", "Central", "North"]
print("New this month:", sorted(set(regions) - set(last_month)))
print("Gone since last month:", sorted(set(last_month) - set(regions)))
They print:
New this month: ['East', 'West']
Gone since last month: ['Central']
Converting both lists to sets removes the duplicate North entries, and -
keeps what is in the first set but not the second. The order of the operands
matters: swapping them answers the other question.
Understanding check
- A list: the order matters and you may append new readings.
- A tuple: two values that belong together and should not change.
- A dictionary: you look prices up by product code, not by position.
- A set: each code should appear once, and the question is membership.