Check your understanding of the previous reading: which types are mutable or immutable, and what happens when you call a mutating method.

Question 1

Identify each of the following as mutable or immutable.
String
List
Integer
Boolean

Question 2

True or false: calling a method always changes the value of the variable you called it on. For example, does the following code change the value of the variable name?

name = "Klaus"
name.lower()

Select one answer, then check.

  • Not quite. Strings are immutable: name.lower() builds and returns a new, lowercased string, but nothing assigns that new string back to name, so name is unchanged.
  • Correct. name stays "Klaus" after this code runs. Only mutable types (like lists) can be changed in place by a method call; for an immutable type like a string, you must assign the method's result back to the variable, e.g. name = name.lower().

Question 3

What value will the variable longer_list have after the following code runs?

longer_list = [1, 2]
longer_list = longer_list.append(3)

Select one answer, then check.

  • Not quite. .append(3) does add 3 to the list in place, but the second line then overwrites longer_list with whatever .append() returns, not with the list itself.
  • Not quite. The list itself really is changed by .append(3) - the problem is what happens to the variable right after.
  • Not quite. .append() mutates the list and returns None, not the value that was appended.
  • Correct. .append() mutates the list in place and then returns None. Assigning that return value back to longer_list overwrites the (correctly updated) list with None.
  • Not quite. .append() always adds its argument to the end of the list, never the front.