Informatics Practices · Ch 4 — Working with Lists and Dictionaries
Lists are Mutable
Lists are Mutable
The definition of a list calls it an ordered sequence which is mutable — and mutability is the property this section pins down. A mutable object is one whose contents can be changed after it has been created. A list, once built, is not frozen: you can replace an element with a new value, and the list simply carries on with its updated contents.
What mutability means in practice
Contrast the two sequence types you know. A string consists only of characters and cannot be altered in place — to "change" a string you must build a new one. A list is the opposite: the element sitting at any index can be overwritten by assignment, using the same square-bracket indexing that reads an element.
>>> list1 = [2,4,6,8,10,12]
>>> list1[2] = 100 # replace the element at index 2
>>> print(list1)
[2, 4, 100, 8, 10, 12]
Read the assignment list1[2] = 100 from left to right: at index 2 of list1, store 100. The old value at that position is discarded, every other element stays exactly where it was, and no new list is created — the same list has been modified in place.
Why this matters
- Data that changes over time fits naturally in a list. Marks get corrected, prices get revised, entries get updated — a list absorbs each change directly, element by element.
- Mixed contents stay editable. Since a list may hold integers, floats, strings, tuples or other lists, any of those elements can be individually replaced without disturbing the rest.
- It is the basis of list manipulation. The operations that come later in the chapter — appending, inserting, deleting, updating elements — all rest on the fact that a list is mutable. None of them would be possible on an unchangeable sequence. …