Section 1 of 9

1 Before you start

Before you begin, take a few minutes to check what you already know and how confident you feel. You will see the same questions again at the end of the module — this helps both you and us measure what you have learned. Click an option for every question and confidence rating, then click Next to continue.

Pre-test

You run ages = [3, 1, 2]; result = ages.sort(); print(result). What is printed?

Pre-test

You run nums = [3, 1, 2]; new = sorted(nums); print(nums). What is printed?

Pre-test

You run scores = [80, 90]; scores.append([70, 60]); print(len(scores)). What is printed?

Pre-test

For vitals = {"hr": 78}, what does vitals.get("spo2", 98) return?

Pre-test

After patient = {"age": 54}; patient.update({"age": 55, "site": "NUH"}), what is patient["age"]?

Pre-test

You run tags = {"S1", "S2"}; tags.add("S1"); print(len(tags)). What is printed?

Pre-test

You run allergies = {"latex"}; allergies.discard("peanuts"); print(allergies). What happens?

Pre-test

You run a = [1, 2, 3]; b = a; b.append(4); print(a). What is printed?

Pre-confidence

I can choose between .sort() and sorted() depending on whether I want to change the list in place or get a new list back.

Not at all confident
Fully confident
Pre-confidence

I can predict whether a built-in method modifies the original container in place or returns a new value.

Not at all confident
Fully confident
Pre-confidence

I can explain why writing b = a does not make a copy of a list, and how to make a real, independent copy.

Not at all confident
Fully confident
Section 2 of 9

2 Introduction

So far, you have met the four built-in containers — lists, tuples, dictionaries, and sets — and learned how to read values out of them. Now, we will learn how to change what is inside these containers.

Each container comes with a small kit of built-in methods, and the same dot-method-parentheses applies here too.

As before, try every snippet in the Python Scratchpad on the right. By the end of this part you will know the everyday methods for each container and avoid the one trap that catches every beginner: mistaking a method that changes a container in place for one that returns a new value.

Section 3 of 9

3 List methods

Lists are mutable, which means you can change them in place.

We can broadly separate these methods into three categories:

(a) Adding items to list

  • .append(x) — add x to the end of the list.
  • .extend(other) — add every item of another list to the end.
  • .insert(i, x) — put x at position i, shifting later items right.
Methods to add items to list.
Methods to add items to list.
  • Try with the example below.
Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
patient_ids = ["P001", "P002", "P003"]
patient_ids.append("P004")
patient_ids.extend(["P005", "P006"])
patient_ids.insert(0, "P000")
print(patient_ids)

(b) Removing items to list

  • .remove(x) — remove the first occurrence of x. Raises ValueError if x is not present.
  • .pop() — remove and return the last item; .pop(i) does the same at position i.
Methods to remove items from list.
Methods to remove items from list.
  • Try with the example below.
Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
medications = ["aspirin", "metformin", "lisinopril", "ibuprofen"]
medications.remove("ibuprofen")
last = medications.pop()
first = medications.pop(0)
print(medications, last, first)
  • (c) Reordering items in list
  • .sort() — sort the list in place. Returns None.
  • .reverse() — reverse the list in place. Returns None.
  • sorted(lst) — a built-in function (not a method) that returns a NEW sorted list and leaves the original alone.
Methods to reorder items in list.
Methods to reorder items in list.
  • Try with the example below.
Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
systolic_bp = [142, 118, 135, 128, 150]
ascending_copy = sorted(systolic_bp)
systolic_bp.sort()
systolic_bp.reverse()
print(ascending_copy)
print(systolic_bp)

One trap that catches every beginner: .sort() returns None, not the sorted list. It changes the list in place. If you write sorted_ages = ages.sort() you will end up with sorted_ages equal to None and a sorted ages — not what you wanted. To get the new list out as a value, use the built-in sorted() function instead.

Section 4 of 9

4 Dictionary methods

Dictionaries are mutable too. The methods you will use most often:

(a) Looking up keys or values in dictionary

  • .keys(), .values(), .items() — three views you loop over.
  • .get(key, default) — safe lookup, returns default (or None) if the key is missing.
Methods to look up keys and values in a dictionary.
Methods to look up keys and values in a dictionary.

(b) Modifying/Mutating dictionary

  • .pop(key) — remove and return the value at key.
  • .update(other) — merge another dictionary in, overwriting any keys that already exist.
  • d[k] = v — ordinary assignment adds a new key or replaces an existing one.
Modifying a dictionary.
Modifying a dictionary.
  • Try the sample code below.
Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
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)
Section 5 of 9

5 Set methods

Sets are mutable but, by design, do not have positions, so the methods are about adding and removing values:

  • .add(x) — add a single value. Adding a value already in the set does nothing.
  • .discard(x) — remove x if it is present; do nothing if it is not.
  • .remove(x) — remove x if it is present; raise KeyError if it is not.
  • .update(other) — add every value from another iterable.
Modifying a dictionary.
Modifying a dictionary.
  • Try out these codes!
Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
allergies = {"penicillin", "latex"}
allergies.add("sulfa")
allergies.add("penicillin")
allergies.discard("peanuts")
allergies.remove("latex")
allergies.update(["aspirin", "iodine"])
print(allergies)
Section 6 of 9

6 Tuple methods

Tuples have no methods that change them, because they cannot change. If you need to update a tuple, the answer is to make a new one. The two methods worth remembering are:

  • .count(x) — how many times x appears
  • .index(x) — the position of the first occurrence

Let’s try it out!

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
diagnoses = ["hypertension", "diabetes", "hypertension", "asthma", "hypertension"]
n_hypertension = diagnoses.count("hypertension")
first_diabetes = diagnoses.index("diabetes")
print(n_hypertension, first_diabetes)
Section 7 of 9

7 Copy versus aliasing

One last thing to watch out for. When you write b = a where a is a list, b is not a copy of the list — it is another name for the same list. This is called aliasing. Changing b changes a too, because they point to the same object in memory.

If you want an actual independent copy, write b = a.copy() or b = list(a). The same is true for dictionaries and sets, with d.copy() and set(s) doing the equivalent job.

Aliasing just assigns another name to the same list. Copying creates a separate independent list.
Aliasing just assigns another name to the same list. Copying creates a separate independent list.
Section 8 of 9

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.

Post-test

You run ages = [3, 1, 2]; result = ages.sort(); print(result). What is printed?

Post-test

You run nums = [3, 1, 2]; new = sorted(nums); print(nums). What is printed?

Post-test

You run scores = [80, 90]; scores.append([70, 60]); print(len(scores)). What is printed?

Post-test

For vitals = {"hr": 78}, what does vitals.get("spo2", 98) return?

Post-test

After patient = {"age": 54}; patient.update({"age": 55, "site": "NUH"}), what is patient["age"]?

Post-test

You run tags = {"S1", "S2"}; tags.add("S1"); print(len(tags)). What is printed?

Post-test

You run allergies = {"latex"}; allergies.discard("peanuts"); print(allergies). What happens?

Post-test

You run a = [1, 2, 3]; b = a; b.append(4); print(a). What is printed?

Post-confidence

I can choose between .sort() and sorted() depending on whether I want to change the list in place or get a new list back.

Not at all confident
Fully confident
Post-confidence

I can predict whether a built-in method modifies the original container in place or returns a new value.

Not at all confident
Fully confident
Post-confidence

I can explain why writing b = a does not make a copy of a list, and how to make a real, independent copy.

Not at all confident
Fully confident
Section 9 of 9

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.

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)