Grade 10 Computer Science · State, change and copying

A name is not a box

What is really stored when a value is given a name.

You touched b, and a changed

Two lines of code: a list gets a second name, and an item is added through that second name. Then the first name, which nobody touched, is printed, and the new item is there too. If a name is a box with the value sitting inside, how is that even possible?

The picture most of us start with is that the name is a box, and inside it sits the value. That picture suffices exactly until the moment two names point at the same thing — and then it explains precisely the opposite of what happens. It is worth replacing now, because nearly every bug later in this unit comes from it.

The name holds a reference to the value, not the value itself.
a = [1, 2, 3]
b = a          # not a copy — a second name for the same list

b.append(4)
print(a)       # [1, 2, 3, 4]  — a changed too
print(a is b)  # True — the same object

Why it was built this way

This is not a design error but a deliberate choice. Automatic copying at every assignment would mean that passing a list of a million items to a function copies a million items — a cost no one wants to pay unasked. The language chooses the cheap default and leaves you to ask for a copy when you genuinely need one. The price of that choice is that you have to know about it.

The operationWhat happens
Assigning a name to a nameAnother reference, no copy
Changing through one nameSeen through all of them
An explicit copy requestA new, separate object

Example 1 — why the first name changed

  1. Both names refer to the same list.
  2. The addition was made to the list itself.
  3. So both see it.

Example 2 — when there is no difference

  1. As long as one only reads, there is no difference.
  2. Both pictures give the same answer.
  3. The difference shows up only on change.
Assigning a name to a name adds an arrow, not a box.