Newbie question about reference

Dan Bishop danb_83 at yahoo.com
Sun Mar 23 08:03:07 CET 2003


Tim Smith <tssmith at velocio.com> wrote in message news:<j30q7v4b9fb5tvbialp3ivritis8kirdui at 4ax.com>...
> "Terry Reedy" <tjreedy at udel.edu> wrote:
> >You here bind 'list' to the object [1,2,3].  (Note: DON'T use builtin
> >names as vars unless you have a positive reason for so doing.)
> 
> OK, I had thought that L = [x,y,z] was binding the list L as an
> ordered set of references/pointers to the variables x, y, z. Obviously
> not, as integers are, along with strings etc., immutable types.

It doesn't have anything to do with mutable v. immutable types.  The
same thing happens with

>>> x = [1]
>>> y = [2]
>>> z = [3]
>>> lst = [x, y, z]
>>> lst
[[1], [2], [3]]
>>> y = [0]
>>> lst
[[1], [2], [3]]
>>>

The important thing to remember is that the list created by "list =
[x, y, z]" stores a pointer to the object that y points to (all
variables in Python are pointers in disguise), and *not* the name or
address of the variable "y".

The immutable/mutable distinction matters in situations like

>>> x = [1]
>>> y = [2]
>>> z = [3]
>>> lst = [x, y, z]
>>> lst
[[1], [2], [3]]
>>> lst[1][0] = 0   # mutates the list [2], which is also pointed to
by y
>>> lst
[[1], [0], [3]]
>>> y
[0]
>>>

> This is not clearly explained in the material I have read so far. It's
> emphasized that strings are immutable, but not ints, tho' I suppose it
> should be obvious, especially to one who's thinking in implementation
> terms (I don't think that way :-)

It might not be obvious to those who still use buggy FORTRAN compilers
:-)




More information about the Python-list mailing list