Lecture 18 - Exercises

18A - Variables are References

For each of today’s exercises, give the answer to the exercise and draw the memory diagram at the end of the program.

  1. What does the following program print?

    a = ["foo", "bar"]
    b = a
    c = a[0:2]
    b[1] = "buzz"
    print(a[1], b[1], c[1])
  2. What is the output of each print call in the following program?

    a = [3, 4, 5]
    a.insert(0, 4)
    a[2:] = a[1:4]
    a.remove(4)
    a.append(a.index(5))
    del a[1]
    print(len(a))
  3. Consider the following program:

    a = [3]
    b = a
    a.append(4)
    c = a[0]
    d = b
    a.extend((17, 19))
    x = a[-2:]
    e = x + [4]
    1. How many distinct list objects are created in the course of executing the program above? Be sure to include any lists that are created but not pointed at by any variable.
    2. At the end of the program, how many other variables (not counting a itself) point to the same list as a?

Problems

  1. Implement the following function. Notice that this function returns a new list and leaves in_list unmodified.

    def copy_list(in_list):
        """ Return a new list object containing
            the same elements as in_list.
            Precondition: in_list's contents are
            all immutable. """
    
    # Example usage:
    a = [1, 2, 3, 4]
    b = copy_list(a)
    b[0] = 0
    print(a[0], b[0])
    # prints 1, 0
  2. Implement the following function. Notice that this function does not return a new list, but modifies the given list in place. Because the list object being modified is the same one as the caller passed in, we do not need to return another reference to the same object.

    def snap(avengers):
       """ Remove a randomly chosen half of the
           elements from the given list of avengers
       """
    
    # Example usage:
    a = [1, 2, 3, 4]
    snap(a)
    print(a)
    # prints [2, 3]

    …which brings up an important question: if the world’s population at the time of the snap was odd, did Thanos round up or down?