Explanation of list reference

Ben Finney ben+python at benfinney.id.au
Sat Feb 15 07:21:13 EST 2014


Jussi Piitulainen <jpiitula at ling.helsinki.fi> writes:

> In cheese = spam, cheese is the variable while spam is a variable
> reference and stands for 42.

Oof. This distinction between “variable” and “variable reference” is
bogus and unnecessary, and highlights what is wrong with talking about
“variable” at all.

In the Python code ‘cheese = spam’, “cheese” is a name, and “spam” is a
name. Both of them are references (because all names are references).

The assignment binds the name “cheese” to whatever object the name
“spam” was bound to at that point in time.

In either case, a different kind of reference (for example, a list item)
could have been used. Names are merely one kind of reference.

> > >>> spam = [0, 1, 2, 3, 4, 5]
> > >>> cheese = spam
> > >>> cheese[1] = 'Hello!'
> > >>> spam
> > [0, 'Hello!', 2, 3, 4, 5]
> > >>> cheese
> > [0, 'Hello!', 2, 3, 4, 5]
>
> The first two statements in case 2 are assignments to variables, just
> like in case 1, but the third statement is different: it doesn't
> change the value of the variable (the value is still the same object)
> but it does change the value (replaces one element of the list with
> another).

Again, this distinction is nonsense and confusing.

What is happening in all those assignments is: A reference (the
expression on the left-hand-side of the ‘=’ symbol) is bound to an
object (the value resulting from the expression on the right-hand-side
of the ‘=’ symbol).

In the first two cases, the reference happens to be a name. In the third
case, the reference happens to be a list item.

> Would it help to say that in case 1 the relevant statement acts on the
> variable while in case 2 it acts on the value of the variable? This is
> accurate, I just don't know if it happens to be the thing that helps.

I think not. What would help is to abandon the “variable” baggage, and
focus on what assignment actually does: binds a reference to an object.

> One last thing: a variable is not an object.

Right. Also: a reference is not an object, but a reference always refers
to exactly one object.

-- 
 \         “Science is a way of trying not to fool yourself. The first |
  `\     principle is that you must not fool yourself, and you are the |
_o__)               easiest person to fool.” —Richard P. Feynman, 1964 |
Ben Finney




More information about the Python-list mailing list