3. Lists Are Mutable¶
Unlike strings, lists are mutable. This means we can change an item in a list by accessing it directly as part of the assignment statement. 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.
Here is the same example in codelens so that you can step through the statements and see the changes to the list elements.
By combining assignment with the slice operator we can update several elements at once.
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.
Check your understanding
- [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.
What is printed by the following statements?
alist = [4, 2, 8, 6, 5]
alist[2] = True
print(alist)