list vs tuple

Egbert Bouwman egbert at bork.demon.nl
Sun Apr 1 06:51:43 EDT 2001


Sat, 31 Mar 2001 21:24:33 GMT, deadmeat <root@[127.0.0.1]> pisze:
> >>> a = 1
> >>> b = a
> >>> a = 2
> >>> b
> 1
> 
> >>> a = [1,2,3]
> >>> b = a
> >>> a[0] = 0
> >>> b
> [0, 2, 3]
> 
Coming from Fortran and PL/I, I too have to be careful not to fall
in the reference trap. My way of explaining what happens above
is as follows, but it may not be correct.

In a = 2 you give the instruction to let a refer to something else.

In a[0] = 0 you give the instruction to let a[0] refer to something 
else, but you don't change the reference of a itself: to the list as a whole. 

The name of a list is a reference to a list of references.
With a = ... you change the top-reference, and with a[0] = ...
you only change one of the nested references.

So with a=2 you let a and b refer to different things,
and with a[0]=0 you let a and b still refer to the same 
but changed thing. 

It looks all very consistent, once you remember what = means.
Changing that meaning may produce a minor culture shock.
Something like that happened to me when for the first time 
in my life I saw the statement a = a + 1

egbert




More information about the Python-list mailing list