[noob question] References and copying

Steve Holden steve at holdenweb.com
Fri Jun 9 11:19:19 EDT 2006


zefciu wrote:
> Hello!
> 
> 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.  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?
> 
> Greets to all PyFans
> zefciu

Nope, b is a reference to the same object referenced by a[1], but only 
until you rebind it. Think of assignment (binding) as storing a pointer 
to an object in a name.

So

a = [[2,3],[3,4]]

stores a pointer to a list in "a". The list itself holds two pointers to 
(otherwise anonymous) lists. Then

b = a[1]

make b point to the same object as a[1] does.

At this point you could, for example, execute

b[0] = 42

Then when you printed the value of "a" you would see

[[1, 2], [42, 4]]

and you would see

[42, 4]

as the value of b. But you don't do that, you next do

b = [5, 6]

This stores a reference to an entirely different new list in "b", with 
the results you observe.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Love me, love my blog  http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list