Mutation and memory 0/1

Lesson 18 of 21

Mutation and memory

When two names share one value, and when a change shows up somewhere else.

Part 1 of 9 Two names, one list

Two names for one list

Say you keep a class's test scores in a list and want to try a change without losing the original, so that you can go back to it. The natural first attempt is to save the list under a second name before changing it:

Sign up to run
scores = [70, 85, 90]
backup = scores
scores[0] = 0
print(backup)

It prints [0, 85, 90]: the backup changed along with the scores. The line backup = scores did not copy the list. It bound the name backup to the same list scores is bound to, so the program has one list with two names. A second name for the same object is an alias, and a change made through one alias is seen through the other. To keep a separate list, copy it: backup = scores.copy().

This lesson is about what happens when a value changes while more than one name can reach it: in a function call, in a grid built out of rows, in a loop that changes what it is reading, and in a function that remembers something between calls.

The trouble only arises for values that can change in place. Such values are called mutable: a list, a dictionary and a set can all be changed after they are made. Numbers, strings and tuples are immutable, so an alias of one is harmless. s = s + "!" builds a new string and binds s to it, and another name for the old string still sees the old text.

Python values that can and cannot change in place
TypeMutableChanged in place by
listyesa[0] = 5, a.append(5), a.sort()
dictyesd[key] = value
setyess.add(x)
an object of a class you wroteyesp.x = 5
int, float, boolnonothing: x += 1 binds x to a new number
strnonothing: s + "!" builds a new string
tuplenonothing, though a list stored in a tuple can still change: t[0].append(5)

That is also why a dictionary can use the tuple (2, 3) as a key and not the list [2, 3]. A dictionary finds an entry by a hash computed from its key, so a key that changed after it was stored would no longer be found.

Step through sharing and copying

The diagram steps through three short programs with two names, a and b. Each name is drawn as an arrow to a list in the Objects column.

Use the left and right arrow keys to step, Home for the first step and End for the last.

  1. a = [1, 2, 3](line that just ran)
  2. b = a(line that runs next)
  3. b[0] = 99
  4. print(a)

Frames

Global current
a
function list

Objects

list[1, 2, 3]

[1, 2, 3] builds a list object, and a is bound to it: the arrow from a points at the list.

Output

Step 1 of 4

In the first program b[0] = 99 changes the one list both arrows point at. In the second, a.copy() made a second list, and the change lands there.

In the third, b = [7, 8] builds a new list and moves the arrow from b to it, and a still points at [1, 2, 3]. Assigning to a name rebinds the name; assigning to an element, or calling a method such as append, changes the object.

Changing elements in a loop

The variable of a for loop is a name like any other, so the same rule applies to it. for x in a: binds x to each element in turn, and x += 1 rebinds x to a new number without touching the list. To change the elements, assign to a[i].

Sign up to run
a = [1, 2, 3]
for x in a:
    x += 1
print(a)
for i in range(len(a)):
    a[i] += 1
print(a)

Identity and equality

Once two names can share a list, there are two different questions to ask about them: do they hold equal values, and are they the same object? The first is equality, asked with ==, and the second is identity, asked with is.

Sign up to run
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b, a is b, a is c)
c.append(4)
print(a, b)

a is b is False, because the two [1, 2, 3] expressions built two lists. c.append(4) grows the one list a and c share, and b keeps its three elements.

Deeper read: adding to a list in place or building a new one

b = b + [3] builds a new list and rebinds b to it, so an alias of the old list does not see the 3. b += [3] adds 3 to the list b already points at, the way b.append(3) does, so every alias sees it.