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.
You run ages = [3, 1, 2]; result = ages.sort(); print(result). What is printed?
You run nums = [3, 1, 2]; new = sorted(nums); print(nums). What is printed?
You run scores = [80, 90]; scores.append([70, 60]); print(len(scores)). What is printed?
For vitals = {"hr": 78}, what does vitals.get("spo2", 98) return?
After patient = {"age": 54}; patient.update({"age": 55, "site": "NUH"}), what is patient["age"]?
You run tags = {"S1", "S2"}; tags.add("S1"); print(len(tags)). What is printed?
You run allergies = {"latex"}; allergies.discard("peanuts"); print(allergies). What happens?
You run a = [1, 2, 3]; b = a; b.append(4); print(a). What is printed?
I can choose between .sort() and sorted() depending on whether I want to change the list in place or get a new list back.
I can predict whether a built-in method modifies the original container in place or returns a new value.
I can explain why writing b = a does not make a copy of a list, and how to make a real, independent copy.
2 Introduction
So far, you have read values from containers. Now you will change what is inside them.
Each container has its own tools, called methods. A method is a function that belongs to a value. For a function like print(), the value goes inside the round brackets. For a method, the value comes first, then a dot, then the method name and round brackets.
labs = {"sodium": 139, "potassium": 4.1}
print(labs) # {'sodium': 139, 'potassium': 4.1}
potassium = labs.get("potassium")
print(potassium) # 4.1The method .get() only reads the dictionary. Other methods change the container itself. This is called changing it in place.
Try every example in the Python Scratchpad on the right.
3 List methods
Most list methods change the list in place.
To add an item x to the end, use .append(x).
waiting_list = ["Tan", "Lim", "Kumar"]
waiting_list.append("Wong")
print(waiting_list) # ['Tan', 'Lim', 'Kumar', 'Wong']The .append() line has no equals sign. This is because the method changes the list itself. To add every item of another list, use .extend(other).
waiting_list = ["Tan", "Lim", "Kumar"]
waiting_list.extend(["Chua", "Ng"])
print(waiting_list) # ['Tan', 'Lim', 'Kumar', 'Chua', 'Ng']With .append(), the whole list goes in as one item. The result is a list inside the list.
waiting_list = ["Tan", "Lim", "Kumar"]
waiting_list.append(["Chua", "Ng"])
print(waiting_list) # ['Tan', 'Lim', 'Kumar', ['Chua', 'Ng']]To put item x at position i, use .insert(i, x). The later items move one place to the right.
waiting_list = ["Tan", "Lim", "Kumar"]
waiting_list.insert(0, "Ong")
print(waiting_list) # ['Ong', 'Tan', 'Lim', 'Kumar']
Try all three below.
Try this snippet in the Python Scratchpad on the right.
patient_ids = ["P001", "P002", "P003"]
patient_ids.append("P004")
patient_ids.extend(["P005", "P006"])
patient_ids.insert(0, "P000")
print(patient_ids)
To remove an item by value, use .remove(x). It removes the first item that equals x.
waiting_list = ["Tan", "Lim", "Kumar"]
waiting_list.remove("Lim")
print(waiting_list) # ['Tan', 'Kumar']If x is not in the list, Python raises a ValueError.
waiting_list = ["Tan", "Kumar"]
waiting_list.remove("Lee")
# ValueError: list.remove(x): x not in listTo remove an item and get it back, use .pop(). It removes the last item. With a position, .pop(i) removes the item at position i.
waiting_list = ["Tan", "Lim", "Kumar", "Wong"]
print(waiting_list.pop()) # Wong
next_patient = waiting_list.pop(0)
print(next_patient) # Tan
print(waiting_list) # ['Lim', 'Kumar']To remove every item, use .clear(). The list still exists. It is now empty.
waiting_list = ["Tan", "Lim", "Kumar"]
waiting_list.clear()
print(waiting_list) # []
Try .remove() and .pop() below.
Try this snippet in the Python Scratchpad on the right.
medications = ["aspirin", "metformin", "lisinopril", "ibuprofen"]
medications.remove("ibuprofen")
last = medications.pop()
first = medications.pop(0)
print(medications, last, first)
Try .clear() below.
Try this snippet in the Python Scratchpad on the right.
vaccine_doses = ["dose_1", "dose_2", "dose_3"]
vaccine_doses.clear()
print(vaccine_doses)
To put a list in order, use .sort().
pulse_readings = [88, 64, 101, 76, 93]
pulse_readings.sort()
print(pulse_readings) # [64, 76, 88, 93, 101]The method .reverse() turns the list around. It does not sort it.
pulse_readings = [88, 64, 101, 76, 93]
pulse_readings.reverse()
print(pulse_readings) # [93, 76, 101, 64, 88]The function sorted() gives back a new list in order. The original list stays as it was.
pulse_readings = [88, 64, 101, 76, 93]
ordered = sorted(pulse_readings)
print(ordered) # [64, 76, 88, 93, 101]
print(pulse_readings) # [88, 64, 101, 76, 93]
Try these below.
Try this snippet in the Python Scratchpad on the right.
systolic_bp = [142, 118, 135, 128, 150]
ascending_copy = sorted(systolic_bp)
systolic_bp.sort()
systolic_bp.reverse()
print(ascending_copy)
print(systolic_bp)
A list method that changes the list in place gives back None. The one exception is .pop(). So .sort() gives back None. Here the result is assigned back to pulse_readings:
pulse_readings = [88, 64, 101, 76, 93]
pulse_readings = pulse_readings.sort()
print(pulse_readings) # None
print(pulse_readings[0])
# TypeError: 'NoneType' object is not subscriptableThe list was sorted. Then the name pulse_readings was set to None. To get the list in order, write pulse_readings.sort() on a line of its own. To get a new list in order, use sorted() and give the result a name.
4 Dictionary methods
Dictionaries can change in place too. Some methods only read a dictionary.
The methods .keys(), .values() and .items() give you the keys, the values, and the key-value pairs. The example uses list() to show them as lists.
labs = {"sodium": 139, "potassium": 4.1}
print(list(labs.keys())) # ['sodium', 'potassium']
print(list(labs.values())) # [139, 4.1]
print(list(labs.items())) # [('sodium', 139), ('potassium', 4.1)]The method .get(key) looks up a key. A missing key gives back None, not an error. With .get(key, default), a missing key gives back default.
labs = {"sodium": 139, "potassium": 4.1}
print(labs.get("potassium")) # 4.1
print(labs.get("glucose")) # None
To remove a pair and get its value, use .pop(key).
labs = {"sodium": 139, "potassium": 4.1, "creatinine": 88}
withdrawn = labs.pop("creatinine")
print(withdrawn) # 88
print(labs) # {'sodium': 139, 'potassium': 4.1}The del keyword also removes a pair. It gives nothing back.
labs = {"sodium": 139, "potassium": 4.1, "creatinine": 88}
del labs["creatinine"]
print(labs) # {'sodium': 139, 'potassium': 4.1}Try del below.
Try this snippet in the Python Scratchpad on the right.
patient = {"id": "P001", "age": 54, "site": "NUH"}
del patient["site"]
print(patient)
To add or replace pairs, use .update(other). A new key is added. An existing key gets the new value.
labs = {"sodium": 139, "potassium": 4.1}
labs.update({"sodium": 141, "urea": 5.2})
print(labs) # {'sodium': 141, 'potassium': 4.1, 'urea': 5.2}Assignment, d[k] = v, does the same for one pair.
labs = {"sodium": 139, "potassium": 4.1}
labs["glucose"] = 5.4
labs["potassium"] = 4.4
print(labs) # {'sodium': 139, 'potassium': 4.4, 'glucose': 5.4}
Try all of these below.
Try this snippet in the Python Scratchpad on the right.
vitals = {"hr": 78, "sbp": 120, "temp": 36.8}
print(list(vitals.keys()), list(vitals.values()))
spo2 = vitals.get("spo2", 98)
vitals.update({"spo2": 97, "hr": 82})
vitals["rr"] = 16
removed_temp = vitals.pop("temp")
print(vitals, spo2, removed_temp)
5 Set methods
Sets can change in place too. A set has no positions. So its methods work on values.
To add a value, use .add(x). Adding a value already there changes nothing. The examples use sorted(). This is because a set has no order.
gene_panel = {"BRCA1", "BRCA2", "TP53"}
gene_panel.add("PALB2")
gene_panel.add("TP53")
print(sorted(gene_panel)) # ['BRCA1', 'BRCA2', 'PALB2', 'TP53']To remove a value, use .discard(x). It does nothing if x is missing.
gene_panel = {"BRCA1", "BRCA2", "TP53"}
gene_panel.discard("BRCA2")
gene_panel.discard("MLH1")
print(sorted(gene_panel)) # ['BRCA1', 'TP53']The method .remove(x) also removes x. It raises a KeyError if x is missing.
gene_panel = {"BRCA1", "BRCA2", "TP53"}
gene_panel.remove("MLH1")
# KeyError: 'MLH1'To add every value from a list or another set, use .update(other). Values already in the set are skipped.
gene_panel = {"BRCA1", "BRCA2", "TP53"}
gene_panel.update(["CHEK2", "ATM", "BRCA1"])
print(sorted(gene_panel)) # ['ATM', 'BRCA1', 'BRCA2', 'CHEK2', 'TP53']
Try all four below.
Try this snippet in the Python Scratchpad on the right.
allergies = {"penicillin", "latex"}
allergies.add("sulfa")
allergies.add("penicillin")
allergies.discard("peanuts")
allergies.remove("latex")
allergies.update(["aspirin", "iodine"])
print(allergies)
6 Tuple methods
A tuple cannot change. So it has no methods that change it. To update a tuple, make a new tuple with the same name.
bp = (128, 84)
bp = (132, 86)
print(bp) # (132, 86)A tuple has two methods. The .count(x) method tells you how many times x appears. The .index(x) method gives the position of the first x.
triage_colours = ("green", "yellow", "green", "green", "red", "yellow")
print(triage_colours.count("green")) # 3
print(triage_colours.index("red")) # 4Try both below.
Try this snippet in the Python Scratchpad on the right.
diagnoses = ("hypertension", "diabetes", "hypertension", "asthma", "hypertension")
n_hypertension = diagnoses.count("hypertension")
first_diabetes = diagnoses.index("diabetes")
print(n_hypertension, first_diabetes)
Try it · Method sorter
Does it change the variable, give something back, or both?
Some methods change the value they belong to. Others leave it alone and hand you a result. Tap an answer for each line.
7 Copy versus aliasing
To keep the readings as a baseline before sorting, you might write baseline = pulse_readings. This does not make a copy. It gives the same list a second name. This is called aliasing.
pulse_readings = [88, 64, 101, 76, 93]
baseline = pulse_readings
pulse_readings.sort()
print(baseline) # [64, 76, 88, 93, 101]The baseline is sorted too. This is because both names point at one list. To keep a separate copy, write pulse_readings.copy() or list(pulse_readings).
pulse_readings = [88, 64, 101, 76, 93]
baseline = pulse_readings.copy()
pulse_readings.sort()
print(baseline) # [88, 64, 101, 76, 93]
print(pulse_readings) # [64, 76, 88, 93, 101]Dictionaries and sets behave the same way. For a dictionary, use d.copy(). For a set, use s.copy() or set(s).

8 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.
You run ages = [3, 1, 2]; result = ages.sort(); print(result). What is printed?
You run nums = [3, 1, 2]; new = sorted(nums); print(nums). What is printed?
You run scores = [80, 90]; scores.append([70, 60]); print(len(scores)). What is printed?
For vitals = {"hr": 78}, what does vitals.get("spo2", 98) return?
After patient = {"age": 54}; patient.update({"age": 55, "site": "NUH"}), what is patient["age"]?
You run tags = {"S1", "S2"}; tags.add("S1"); print(len(tags)). What is printed?
You run allergies = {"latex"}; allergies.discard("peanuts"); print(allergies). What happens?
You run a = [1, 2, 3]; b = a; b.append(4); print(a). What is printed?
I can choose between .sort() and sorted() depending on whether I want to change the list in place or get a new list back.
I can predict whether a built-in method modifies the original container in place or returns a new value.
I can explain why writing b = a does not make a copy of a list, and how to make a real, independent copy.
9 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?