Skip to content

Computer Science · Ch 9 — Lists

Lists are Mutable

9.1.2

Lists are Mutable

Lists in Python are mutable: the contents of a list can be changed after the list has been created. This is the single most important property separating a list from a string — a string, once built, can never be altered in place, but a list can.

Replacing an element in place

To change an element, assign a new value to its position using ordinary index notation on the left-hand side of an assignment:

# a list of four fruits
>>> fruits = ['Apple', 'Mango', 'Guava', 'Papaya']

# change/override the fourth element (index 3)
>>> fruits[3] = 'Banana'

>>> fruits          # the list shows the modification
['Apple', 'Mango', 'Guava', 'Banana']

No new list is created here. The same list object is modified: the element that used to sit at index 3 is discarded and the new value takes its place, while every other element stays untouched.

Why mutability matters

  • You can correct, update or overwrite individual entries of a list without rebuilding the whole list. …