1 Before you start
This is not graded, and it does not count towards anything. Answer every question even if you are only guessing — having a go at something before you have been taught it is one of the best ways to remember it afterwards. The lesson ends with another short check, and there you will be shown the correct answer for anything you missed. Choose an option for every question and confidence rating, then click Submit answers.
Given ages = [54, 67, 71, 49], what does ages[-1] return?
Given genes = ["APOE", "TREM2", "BIN1", "MAPT"], what does genes[1:3] return?
coords = (4, 9) is a tuple. What happens when you run coords[0] = 5?
A patient dictionary is patient = {"id": "P001", "age": 54}. Which line safely returns None instead of raising KeyError when "middle_name" is missing?
In the loop for k, v in patient.items():, what do k and v hold on each pass?
You write samples = {"S1", "S1", "S2"}. What does len(samples) return?
With a = {"P1", "P2", "P3"} and b = {"P2", "P3", "P4"}, what does a - b return?
You need a collection of unique patient IDs with no duplicates and no guaranteed order. Which container fits best?
I can explain to a peer when to use a list, a tuple, a dictionary, or a set.
I can write a loop that walks a dictionary and uses both the key and the value on each iteration.
I can use .get() to read a value from a dictionary safely without raising KeyError.
2 Introduction
Once you can store a single value in a variable, the next question is how to store many values together. A container keeps a group of values under one name. Python has four built-in containers: lists, tuples, dictionaries and sets.
This lesson shows how to create each container and how to get values from it. It also shows which job each container suits, so you can choose the right one. Try every example in the Python Scratchpad on the right.

3 Lists
Suppose you record a heart rate at each of five clinic visits. A list keeps the values together under one name. You write the values inside square brackets, separated by commas:
heart_rates = [88, 64, 101, 76, 93]
print(heart_rates) # [88, 64, 101, 76, 93]Printing the list shows the values in the order you wrote them.
Try this snippet in the Python Scratchpad on the right.
ages = [54, 67, 71, 49]
genes = ["APOE", "TREM2", "BIN1"]
print(ages)
print(genes)
3.1 Lists and Indexes
Every item in a list has a position, called its index. This is because a list keeps its order. The first item is at index 0, not 1.
To get an item, write its index in square brackets after the list name. A negative index counts from the end. Index -1 is the last item:
heart_rates = [88, 64, 101, 76, 93]
print(heart_rates[0]) # 88
print(heart_rates[1]) # 64
print(heart_rates[-1]) # 93
print(heart_rates[-2]) # 76Try this snippet in the Python Scratchpad on the right.
meds = ["aspirin", "insulin", "warfarin"]
print(meds[0])
print(meds[-1])
print(meds[-2])
Try this snippet in the Python Scratchpad on the right.
temps_celsius = [37.2, 38.1, 38.9, 38.4, 37.6]
print(temps_celsius[0])
print(temps_celsius[2])
print(temps_celsius[-1])
print(temps_celsius[-2])
The len() function gives the number of items in a list. A list of five items has the indexes 0 to 4. Index 5 is past the end, so Python raises an IndexError:
heart_rates = [88, 64, 101, 76, 93]
print(len(heart_rates)) # 5
print(heart_rates[5])
# IndexError: list index out of rangeSquare brackets do two different jobs. On their own, they build a list. Written straight after a name, they look something up.
A list can hold a mix of types, including other lists. In practice, a list usually holds only numbers or only text.
3.2 Slicing a list
When you want a piece of a list, use a slice. Write two indexes in the square brackets, with a colon between them. The slice includes the first index and leaves out the second.

heart_rates = [88, 64, 101, 76, 93]
print(heart_rates[1:4]) # [64, 101, 76]
print(heart_rates[:3]) # [88, 64, 101]
print(heart_rates[-2:]) # [76, 93]The first slice starts at index 1 and stops before index 4, so it has three items. A blank first index starts at the first item. A blank second index runs to the end.
Read the code carefully and type what you think it will print. Click Submit prediction for AI tutor feedback comparing your prediction against the real output, then click Reveal actual output to run the snippet yourself and see what happens.
snps = ["rs1", "rs2", "rs3", "rs4", "rs5"]
print(snps[1:3])
print(snps[:2])
print(snps[-2:])
A third number after a second colon is the step. A step of 2 takes every second item. A step of -1 gives the list in reverse order:
heart_rates = [88, 64, 101, 76, 93]
print(heart_rates[::2]) # [88, 101, 93]
print(heart_rates[::-1]) # [93, 76, 101, 64, 88]Try this snippet in the Python Scratchpad on the right.
antibiotics = ["amoxicillin", "doxycycline", "ciprofloxacin", "ceftriaxone", "vancomycin", "meropenem"]
print(antibiotics[:2])
print(antibiotics[-2:])
print(antibiotics[2:5])
print(antibiotics[::2])
Try it · Slice explorer
Which items does a slice pick?
Type a position like 2 or a slice like 1:4, then press Show. The numbers above each box count from the front; the numbers below count from the back.
weeks = ["wk0", "wk4", "wk8", "wk12", "wk16", "wk24"]
Can you make these?
3.3 Looping over a list
Often you want to do the same thing to every item in a list. Going through the items one at a time is called looping.

You write for, then a name that you choose, then in, then the list and a colon:
heart_rates = [88, 64, 101, 76, 93]
for heart_rate in heart_rates:
print(f"{heart_rate} bpm") # 88 bpm, 64 bpm, 101 bpm, 76 bpm, 93 bpmThe indented lines run once for each item. Each time, the name holds the next item. So the loop above prints five lines. Inside the loop, an if line can test each item:
heart_rates = [88, 64, 101, 76, 93]
for heart_rate in heart_rates:
if heart_rate > 100:
print(f"{heart_rate} bpm: high") # 101 bpm: highNow arrange the lines below into a working loop.
All the lines you need are in the Line bank on the left — some may be distractors you should leave behind. Drag the lines you need into the Your solution column on the right, in the correct order, then click Check.
Task: Given a list of patient temperatures in Celsius, count how many readings are above 38.0 (indicating fever).
if t > 38.0:if t < 38.0:fever_count = fever_count + 1temps = [36.5, 38.2, 37.1, 39.0, 36.8]fever_count = 0print(fever_count)for t in temps:fever_count == fever_count + 1for t in temps
- Drop lines here, in order.
Try this snippet in the Python Scratchpad on the right.
hba1c_values = [5.4, 6.1, 7.8, 5.9, 8.5]
for hba1c in hba1c_values:
if hba1c >= 6.5:
print(f"{hba1c}%: diabetic range")
else:
print(f"{hba1c}%: below the diabetic range")
4 Tuples
A tuple looks almost the same as a list, but it uses round brackets. You read from a tuple in the same way, with an index in square brackets:
bp_reading = (128, 84)
print(bp_reading[0]) # 128
print(bp_reading[1]) # 84A tuple suits values with a fixed shape, such as a blood pressure reading. This is because no later line of code can change its parts by accident.
You can unpack a tuple into separate names in one line. You need one name for each item. The items go to the names in order:
bp_reading = (128, 84)
systolic, diastolic = bp_reading
print(systolic) # 128
print(diastolic) # 84Try this snippet in the Python Scratchpad on the right.
patient = ("P-1042", 58, "O+", 1.72, 68.5)
patient_id, age, blood_type, height_m, weight_kg = patient
bmi = weight_kg / (height_m ** 2)
print(f"{patient_id}: BMI = {round(bmi, 1)}")
A tuple can be sliced too.
Try this snippet in the Python Scratchpad on the right.
hr_week = (72, 78, 75, 82, 70, 68, 74)
print(hr_week[0])
print(hr_week[-1])
print(hr_week[:3])
print(hr_week[-3:])
print(hr_week[::-1])
Read the code carefully and type what you think it will print. Click Submit prediction for AI tutor feedback comparing your prediction against the real output, then click Reveal actual output to run the snippet yourself and see what happens.
bp = (120, 80, 72)
print(bp[:2])
print(bp[-1])
A list can change after it is made, so it is mutable. A tuple cannot change, so it is immutable. Below, the same change works on a list but raises a TypeError on a tuple:
bp_list = [128, 84]
bp_list[1] = 90
print(bp_list) # [128, 90]
bp_tuple = (128, 84)
bp_tuple[1] = 90
# TypeError: 'tuple' object does not support item assignment5 Dictionaries
A dictionary finds a value by its name instead of its position. Here is a dictionary of three lab results:
labs = {"sodium": 139, "potassium": 4.1, "creatinine": 88}
print(labs["potassium"]) # 4.1
A dictionary stores pairs. Each pair is a key and a value, joined by a colon. Pairs sit inside curly braces, separated by commas. To get a value, write the dictionary name and the key in square brackets.
Try this snippet in the Python Scratchpad on the right.
patient = {"id": "P001", "age": 54, "gene": "APOE"}
print(patient["id"])
print(patient["age"])
print(len(patient))
Keys are usually short strings. A value can be a number, a string or a list. When it is a list, you reach inside it with two lookups in a row:
record = {"ward": "B4", "heart_rates": [88, 64, 101, 76, 93]}
print(record["heart_rates"]) # [88, 64, 101, 76, 93]
print(record["heart_rates"][-1]) # 93If you ask for a key that is not in the dictionary, Python raises a KeyError:
labs = {"sodium": 139, "potassium": 4.1, "creatinine": 88}
print(labs["glucose"])
# KeyError: 'glucose'- To avoid the error, test for the key first with the
inoperator. This checks the keys, not the values. - Or use the
.get()method, which returnsNoneinstead of raising an error.Noneis the Python value for no value at all..get()can also take a second value, which it returns instead ofNone.
labs = {"sodium": 139, "potassium": 4.1, "creatinine": 88}
print("glucose" in labs) # False
print(labs.get("glucose")) # None
print(labs.get("glucose", "not measured")) # not measuredFix the code in the exercise below.
The code below is broken. Type a fixed version into the editor, then click Run & check. Success means your code runs without errors and produces output. Use Show hint only if you get stuck.
patient = {"id": "P001", "age": 54}
print(patient["middle_name"])
- Use .get(): print(patient.get("middle_name")) ★
- Wrap the print in try/except ValueError
- Add quotes around the key: patient["'middle_name'"]
5.1 Looping over a dictionary
By default, a loop over a dictionary takes each key in turn:
labs = {"sodium": 139, "potassium": 4.1, "creatinine": 88}
for test in labs:
print(test) # sodium, potassium, creatinine- To loop over each key and its value together, use
.items(). - To loop over the values only, use
.values().
labs = {"sodium": 139, "potassium": 4.1, "creatinine": 88}
for test, result in labs.items():
print(f"{test}: {result}") # sodium: 139, potassium: 4.1, creatinine: 88
for result in labs.values():
print(result) # 139, 4.1, 88Each pair from .items() is a tuple, which the loop unpacks into two names. So test holds the key and result holds its value.
Try this snippet in the Python Scratchpad on the right.
vitals = {"heart_rate": 72, "systolic_bp": 118, "temp_c": 36.8}
for measurement, value in vitals.items():
print(f"{measurement}: {value}")
for v in vitals.values():
print(v)
6 Sets
A set holds unique values, with no duplicates and no order. It uses curly braces like a dictionary, but holds values only. A repeated value is kept once, and Python gives no warning:
wards_with_cases = {2, 5, 2, 3, 5}
print(wards_with_cases) # {2, 3, 5}
print(wards_with_cases[0])
# TypeError: 'set' object is not subscriptableA set has no positions. This is because it has no order. So index 0 raises a TypeError. When you print a set, its values may come out in any order. Three operators compare two sets:
&gives the intersection: the values in both sets.|gives the union: the values in either set.-gives the difference: the values in the first set but not in the second.

Suppose two sets hold the wards that reported an infection in January and in February:
jan_wards = {1, 2, 4, 6}
feb_wards = {2, 6, 7}
print(jan_wards & feb_wards) # {2, 6}
print(jan_wards | feb_wards) # {1, 2, 4, 6, 7}
print(jan_wards - feb_wards) # {1, 4}For the difference, the order of the two sets matters. This is because the result holds values from the first set only.
Try this snippet in the Python Scratchpad on the right.
diabetes = {"P001", "P002", "P003", "P004"}
hypertension = {"P002", "P004", "P005", "P006"}
print(diabetes & hypertension)
print(diabetes | hypertension)
print(diabetes - hypertension)
Try it · Sets
Which patients does each set operator give?
Two sets of patient IDs from one clinic week. Tap an operator to light up the part of the diagram it gives.
A set has no order, so Python may print these IDs in a different order.
7 Check your understanding
You have reached the end of the module. Try the same questions again — your answers here, paired with your pre-test answers, are how we measure what the module taught you. Answer every question and confidence rating, then click Submit and see results to view your score.
Given ages = [54, 67, 71, 49], what does ages[-1] return?
Given genes = ["APOE", "TREM2", "BIN1", "MAPT"], what does genes[1:3] return?
coords = (4, 9) is a tuple. What happens when you run coords[0] = 5?
A patient dictionary is patient = {"id": "P001", "age": 54}. Which line safely returns None instead of raising KeyError when "middle_name" is missing?
In the loop for k, v in patient.items():, what do k and v hold on each pass?
You write samples = {"S1", "S1", "S2"}. What does len(samples) return?
With a = {"P1", "P2", "P3"} and b = {"P2", "P3", "P4"}, what does a - b return?
You need a collection of unique patient IDs with no duplicates and no guaranteed order. Which container fits best?
I can explain to a peer when to use a list, a tuple, a dictionary, or a set.
I can write a loop that walks a dictionary and uses both the key and the value on each iteration.
I can use .get() to read a value from a dictionary safely without raising KeyError.
8 Your results
Here is how your post-test answers compare with your pre-test answers. The pre/post pairing is the most reliable way to see what this module actually taught you.
Submit the post-test to see your results.
What is the one thing from this module that is still unclear to you?