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.
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 objectWhy 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 operation | What happens |
|---|---|
| Assigning a name to a name | Another reference, no copy |
| Changing through one name | Seen through all of them |
| An explicit copy request | A new, separate object |
Example 1 — why the first name changed
- Both names refer to the same list.
- The addition was made to the list itself.
- So both see it.
Example 2 — when there is no difference
- As long as one only reads, there is no difference.
- Both pictures give the same answer.
- The difference shows up only on change.