Discussion 6: Mutability

If there are fewer than 3 people in your group, feel free to merge your group with another group in the room.

Now switch to Pensieve:

  • Everyone: Go to pensieve.co, log in with your @berkeley.edu email, and enter your group number (which was in the email that assigned you to this lab).

Once you're on Pensieve, you don't need to return to this page; Pensieve has all the same content (but more features). If for some reason Penseive doesn't work, return to this page and continue with the discussion.

Getting Started

Say your name and share a favorite place on the Berkeley campus or surrounding city that you've discovered. Try to pick a place that others might not have been yet. (But if the room you're in now is your favorite place on campus, that's ok too.)

McCone Hall has a nice view from the 5th floor balcony.

List Mutation

The two most common mutation operations for lists are item assignment and the append method.
>>> s = [1, 3, 4]
>>> t = s  # A second name for the same list
>>> t[0] = 2  # this changes the first element of the list to 2, affecting both s and t
>>> s
[2, 3, 4]
>>> s.append(5)  # this adds 5 to the end of the list, affecting both s and t
>>> t
[2, 3, 4, 5]

There are many other list mutation methods:

  • append(elem): Add elem to the end of the list. Return None.
  • extend(s): Add all elements of iterable s to the end of the list. Return None.
  • insert(i, elem): Insert elem at index i. If i is greater than or equal to the length of the list, then elem is inserted at the end. This does not replace any existing elements, but only adds the new element elem. Return None.
  • remove(elem): Remove the first occurrence of elem in list. Return None. Errors if elem is not in the list.
  • pop(i): Remove and return the element at index i.
  • pop(): Remove and return the last element.

Q1: Nested Lists

The mathematical constant e is 2.718281828...

Draw an environment diagram to determine what is printed by the following code.

If you have questions, ask them instead of just looking up the answer! First ask your group, and then the course staff.

Q2: Apply in Place

Implement apply_in_place, which takes a one-argument function fn and a list s. It modifies s so that each element is the result of applying fn to that element. It returns None.

Your Answer
Run in 61A Code
Solution
def apply_in_place(fn, s):
    """Replace each element x of s with fn(x).

    >>> original_list = [5, -1, 2, 0]
    >>> apply_in_place(lambda x: x * x, original_list)
    >>> original_list
    [25, 1, 4, 0]
    """
    for i in range(len(s)):
        s[i] = fn(s[i])
One approach is to use for i in range(...) to iterate over the indices (positions) of s.

Q3: Word Rope

Definition: A rope in Python is a list containing only one-letter strings except for the last element, which may either be a one-letter string or a rope.

Implement word_rope, a Python function that takes a non-empty string s containing only letters and spaces that does not start or end with a space. It returns a rope containing the letters of s in which each word is in a separate list.

Important: You may not use slicing or the split, find, or index methods of a string. Solve the problem using list operations.

Reminder: s[-1] evaluates to the last element of a sequence s.

Your Answer
Run in 61A Code
Solution
def word_rope(s):
    """Return a rope of the words in string s.

    >>> word_rope('the ref was wrong')
    ['t', 'h', 'e', ['r', 'e', 'f', ['w', 'a', 's', ['w', 'r', 'o', 'n', 'g']]]]
    """
    assert s and s[0] != ' ' and s[-1] != [ ]
    result = []
    word = result
    for x in s:
        if x == ' ':
            word.append([])
            word = word[-1]
        else:
            word.append(x)
    return result
In this implementation, result is a rope and word is a list within that rope which is still being constructed. When x is a space, add an empty list to the end of word and assign word to this empty list. Otherwise, add x to the end of word.

Document the Occasion

Please all fill out the attendance form (one submission per person per week).