Lecture 15 - Exercises

15A - List Basics

Suppose that I’ve created a list as follows: folks = ["Ada", "Alan", "Grace", "Frank"]

For each of the following expressions, write what it evaluates to.

  1. "Ada" in folks
  2. "Frank" in folks[1:3]
  3. len(folks[1:4]) == 3
  4. "Alan" in (folks + ["Roy"])[2:]
  5. len(folks[1:2]) * 4 == 8
  6. folks[4:] + folks[1:2]
  7. folks[3] + folks[1]

15B - List Methods and Mutability

  1. Write the contents of a (as it would be printed by Python) after each line of the following program.

    a = ["Abe", "Ike"]
    a.append("JFK")
    a.extend(["FDR", "Geo"])
    a[0] = a[:2]
    a[1:2] = a[3:]
    a[0][1] = a[3]
  2. Execute the numbered lines below in order; if one causes an error, assume it is skipped before continuing on. List all the line numbers that do not cause errors.

    1  A = ["Tony", "Steve"]
    2  B = ("Tony", "Steve")
    3  C = "Tony, Steve"
    4  A[0] = "Thor"
    5  B[0] = "Thor"
    6  print(A[0] + C[:4])
    7  C[0] = "P"
    8  A[1:] = ["Bruce", "Natasha"]
  3. What does the following print? Be sure to check your answer on this one using Thonny.

a = [1, 2, 3]
b = a + [4, 5]
a.append("abc")
a.extend("abc")
print(a)