Sub topic 4
Lists are mutable
This chapter assumes you can run Python code, assign variables, and call methods. It explains what "mutable" means for a list and the behaviors that follow from it.
What mutable means
A mutable object can change after it is created, and the change happens to the same object. A list is mutable. A str is not. When you change a list, Python edits the existing list. It does not build a new one.
Assigning to an index
Assigning to an index replaces the item at that position:
colors = ["red", "green", "blue"]
before = id(colors) # id() identifies the object
colors[1] = "yellow"
print(colors) # ['red', 'yellow', 'blue']
print(id(colors) == before) # True: same list, new contentsThe identity did not change. Only the contents did.
Strings behave differently. They reject item assignment:
name = "list"
try:
name[0] = "L"
except TypeError as error:
print(error) # 'str' object does not support item assignmentTo "change" a string, you must build a new one and rebind the name.
In-place methods return None
Most methods that change a list do so in place and return None. A common error is assigning the result:
nums = [3, 1, 2]
nums = nums.append(4) # wrong: append returns None
print(nums) # NoneCall the method on its own line and keep using the original name.
Functions can change your list
Passing a list to a function does not copy it. The function receives a reference to the same object, so changes it makes are visible to the caller:
def add_total(values):
values.append(sum(values))
scores = [3, 4]
add_total(scores)
print(scores) # [3, 4, 7]This is useful when intended. It is a bug when a function modifies its argument by surprise. If a function should not alter its input, have it work on a copy or return a new list.
Mutating versus rebinding
Two lines that look similar can behave very differently. One mutates the existing object. The other creates a new object and points the name at it.
a = [1, 2]
b = a # b refers to the same list as a
a += [3] # += on a list mutates in place
print(b) # [1, 2, 3]
a = a + [4] # + builds a new list, then rebinds a
print(a) # [1, 2, 3, 4]
print(b) # [1, 2, 3]Because b and a shared one list, a += [3] changed what b sees. After a = a + [4], the name a points to a new list, and b keeps the old one. Sharing between names is called aliasing. A later chapter covers it and how to copy lists.
Common errors
- Assigning the return value of an in-place method, which gives you
None. - Expecting a function argument to stay unchanged after the function mutates it.
- Assuming
b = acopies a list. It only adds a second name for it. - Assuming
+=and+on lists are interchangeable.+=mutates, and+creates a new list.
Exercise
Given a = [1, 2] and b = a, what is b after a += [3]? What would b be if the third line were a = a + [3] instead?
Show answer
With a += [3], b is [1, 2, 3], because += mutates the one shared list. With a = a + [3], b stays [1, 2], because + builds a new list and rebinds only a.