Skip to main content

Section 9.8 Lists are Mutable

Now it’s time to see the things that make lists different from strings. Possibly the most important difference is that, unlike strings, lists are mutable. This means we can change an item in a list by accessing it directly as part of an assignment statement. By using the indexing operator (square brackets) on the left side of an assignment, we can update one of the list items.
An assignment to an element of a list is called item assignment. Item assignment does not work for strings. Recall that strings are immutable, as we saw in Section 7.12.
Here is the same example in codelens so that you can step through the statements and see the changes to the list elements. Notice that these operations do not create a new list.
By combining assignment with the slice operator, we can update several elements at once. In the following program, we change the second and third elements of the array with one assignment:
We can also remove elements from a list by assigning the empty list to them.
We can even insert elements into a list by squeezing them into an empty slice at the desired location.

Checkpoint 9.8.1.

    What is printed by the following statements?
    a_list = [4, 2, 8, 6, 5]
    a_list[2] = True
    print(a_list)
    
  • [4, 2, True, 8, 6, 5]
  • Item assignment does not insert the new item into the list.
  • [4, 2, True, 6, 5]
  • Yes, the value True is placed in the list at index 2. It replaces 8.
  • Error, it is illegal to assign
  • Item assignment is allowed with lists. Lists are mutable.