[noob question] References and copying

Petr Prikryl prikryl at skil.cz
Tue Jul 4 02:54:35 EDT 2006


"zefciu" wrote in message news:e6c2p5$h7j$1 at inews.gazeta.pl...
> Where can I find a good explanation when does an interpreter copy the
> value, and when does it create the reference.  I thought I understand
> it, but I have just typed in following commands:
>
> >>> a=[[1,2],[3,4]]
> >>> b=a[1]
> >>> b=[5,6]
> >>> a
> [[1, 2], [3, 4]]
> >>> b
> [5, 6]
>
> And I don't understand it.  I thought, that b will be a reference to a,
> so changing b should change a as well.  What do I do wrong.

The assignment always copy the reference, never the value.
After b=a[1] the b refers to the list object [3,4].
After b=[5,6] the earlier binding is forgotten, the new list with
values [5,6] is created and the b is bound to the new list.

But if you did
b[0] = 5
b[1] = 6

then you would get the expected result. The reason is that
b[0] is bound to 3 inside the big list refered by a, and
it is rebound to 5.

The suggested b[:] = [5, 6] is a shortcut for that (in fact,
it is slighly more magical and powerful).


> And a second question - can I create a reference to element of a list of
> floating points and use this reference to change that element?

No. Because the trivial types and also the string type are immutable
(i.e. constant). The list would contain references to the constants.
You cannot change the value of any constant. You have to replace
the reference.

Another possibility is to create your own class that will represent
one floating point value but will be mutable. In other words, the object
of your class will be a container (refered from the list) and its
internal state--the floating number--will be changed using the
method of the container.

pepr





More information about the Python-list mailing list