Section 1

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.

Pre-test

Given ages = [54, 67, 71, 49], what does ages[-1] return?

Pre-test

Given genes = ["APOE", "TREM2", "BIN1", "MAPT"], what does genes[1:3] return?

Pre-test

coords = (4, 9) is a tuple. What happens when you run coords[0] = 5?

Pre-test

A patient dictionary is patient = {"id": "P001", "age": 54}. Which line safely returns None instead of raising KeyError when "middle_name" is missing?

Pre-test

In the loop for k, v in patient.items():, what do k and v hold on each pass?

Pre-test

You write samples = {"S1", "S1", "S2"}. What does len(samples) return?

Pre-test

With a = {"P1", "P2", "P3"} and b = {"P2", "P3", "P4"}, what does a - b return?

Pre-test

You need a collection of unique patient IDs with no duplicates and no guaranteed order. Which container fits best?

Pre-confidence

I can explain to a peer when to use a list, a tuple, a dictionary, or a set.

Not at all confident
Fully confident
Pre-confidence

I can write a loop that walks a dictionary and uses both the key and the value on each iteration.

Not at all confident
Fully confident
Pre-confidence

I can use .get() to read a value from a dictionary safely without raising KeyError.

Not at all confident
Fully confident
Section 2

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.

Four different types of data structures in Python.
Four different types of data structures in Python.
Section 3

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 it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
ages = [54, 67, 71, 49]
genes = ["APOE", "TREM2", "BIN1"]
print(ages)
print(genes)
Section 3.1

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.

Indexing positions in Python.
Indexing positions in Python.

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])  # 76
Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
meds = ["aspirin", "insulin", "warfarin"]
print(meds[0])
print(meds[-1])
print(meds[-2])
Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
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 range

Square 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.

Section 3.2

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.

Slicing a list in Python.
Slicing a list in Python.
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.

Predict the output

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.

Code
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 it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
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"]

Or tap:

Can you make these?

    Section 3.3

    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.

    Looping over a Python list.
    Looping over a Python list.

    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 bpm

    The 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: high

    Now arrange the lines below into a working loop.

    Parsons problem · Count patients with fever from temperature readings

    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).

    Line bank
    • if t > 38.0:
    • if t < 38.0:
    • fever_count = fever_count + 1
    • temps = [36.5, 38.2, 37.1, 39.0, 36.8]
    • fever_count = 0
    • print(fever_count)
    • for t in temps:
    • fever_count == fever_count + 1
    • for t in temps
    Your solution
    • Drop lines here, in order.
    Try it out

    Try this snippet in the Python Scratchpad on the right.

    Try this snippet
    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")
    Section 4

    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])  # 84

    A 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)  # 84
    Try it out

    Try this snippet in the Python Scratchpad on the right.

    Try this snippet
    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 it out

    Try this snippet in the Python Scratchpad on the right.

    Try this snippet
    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])
    Predict the output

    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.

    Code
    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 assignment
    A list is mutable. A tuple is immutable.
    A list is mutable. A tuple is immutable.
    Section 5

    5 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
    Key-value pairs in Python dictionary.
    Key-value pairs in Python dictionary.

    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 it out

    Try this snippet in the Python Scratchpad on the right.

    Try this snippet
    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])  # 93

    If 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 in operator. This checks the keys, not the values.
    • Or use the .get() method, which returns None instead of raising an error. None is the Python value for no value at all. .get() can also take a second value, which it returns instead of None.
    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 measured

    Fix the code in the exercise below.

    Debug & fix

    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.

    Broken code (do not copy verbatim)
    patient = {"id": "P001", "age": 54}
    print(patient["middle_name"])
    Section 5.1

    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, 88

    Each pair from .items() is a tuple, which the loop unpacks into two names. So test holds the key and result holds its value.

    Try it out

    Try this snippet in the Python Scratchpad on the right.

    Try this snippet
    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)
    Section 6

    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 subscriptable

    A 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.
    Different operators for set.
    Different operators for set.

    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 it out

    Try this snippet in the Python Scratchpad on the right.

    Try this snippet
    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.

    fever = {"S01", "S02", "S04", "S07"} rash = {"S02", "S05", "S07", "S09"}
    fever rash S01S04 S02S07 S05S09
    Tap an operator above.

    A set has no order, so Python may print these IDs in a different order.

    Section 7

    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.

    Post-test

    Given ages = [54, 67, 71, 49], what does ages[-1] return?

    Post-test

    Given genes = ["APOE", "TREM2", "BIN1", "MAPT"], what does genes[1:3] return?

    Post-test

    coords = (4, 9) is a tuple. What happens when you run coords[0] = 5?

    Post-test

    A patient dictionary is patient = {"id": "P001", "age": 54}. Which line safely returns None instead of raising KeyError when "middle_name" is missing?

    Post-test

    In the loop for k, v in patient.items():, what do k and v hold on each pass?

    Post-test

    You write samples = {"S1", "S1", "S2"}. What does len(samples) return?

    Post-test

    With a = {"P1", "P2", "P3"} and b = {"P2", "P3", "P4"}, what does a - b return?

    Post-test

    You need a collection of unique patient IDs with no duplicates and no guaranteed order. Which container fits best?

    Post-confidence

    I can explain to a peer when to use a list, a tuple, a dictionary, or a set.

    Not at all confident
    Fully confident
    Post-confidence

    I can write a loop that walks a dictionary and uses both the key and the value on each iteration.

    Not at all confident
    Fully confident
    Post-confidence

    I can use .get() to read a value from a dictionary safely without raising KeyError.

    Not at all confident
    Fully confident
    Section 8

    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.

    Your score

    Submit the post-test to see your results.

    Muddiest point

    What is the one thing from this module that is still unclear to you?

    Rate this module

    Overall, how would you rate this module?

    How likely are you to recommend this module to a peer? (0 = not at all, 10 = extremely likely)