[noob question] References and copying

bruno at modulix onurb at xiludom.gro
Fri Jun 9 12:02:23 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.

Unless you explicitely ask for a copy (either using the copy module or a
specific function or method), you'll get a reference.

>  I thought I understand
> it, but I have just typed in following commands:
> 
> 
>>>>a=[[1,2],[3,4]]

- creates a list object containing 2 list objects, the first one
containing 2 integer objects with respective values 1 and 2, the second
one containing 2 integer objects with respective values 3 and 4

- associates ('binds') the name 'a' with the list object. Now in the
current namespace, 'a' refers to this list.

>>>>b=a[1]

- binds the name 'b' with the second element of [the list bound to] 'a'

>>>>b=[5,6]

- *re*binds 'b' to a new list containing two integer objects with
respective values 5 and 6.

>>>>a
> 
> [[1, 2], [3, 4]]
> 
>>>>b
> 
> [5, 6]


Which is exactly what you asked for (while not being what you thought
you asked for...).

> And I don't understand it.  I thought, that b will be a reference to a,

It was - before you rebind it to another object.

> so changing b should change a as well.

To be pedantic, you don't change 'b'. You can either modify the object
bound to 'b' (which you did not) or rebind 'b' to another object (which
you did).

>  What do I do wrong.  

confusing rebinding a name and modifying an object.

Try this to better see what happens
NB :
 - id() returns the unique identifier of an object - actually, in
CPython, it's memory address,
- 'is' test for identity ( a is b <=> id(a) == id(b)

>>> a = [[1, 2], [3, 4]]
>>> id(a)
46912496884192
>>> id(a[1])
46912496914656
>>> b = a[1]
>>> id(b)
46912496914656
>>> b is a[1]
True
>>> b = [5, 6]
>>> id(b)
46912496915520
>>> b is a[1]
False
>>>

Now to modify a[1] thru b :
>>> b = a[1]
>>> id(b)
46912496914656
>>> b is a[1]
True
>>> # add an item
>>> b.append(5)
>>> b
[3, 4, 5]
>>> b is a[1]
True
>>> a[1]
[3, 4, 5]
>>> # remove the first item
>>> del b[0]
>>> a[1]
[4, 5]
>>> # replace actual content with something else
>>> b[:] = [5, 6]
>>> b
[5, 6]
>>> b is a[1]
True
>>> a
[[1, 2], [5, 6]]
>>>


> 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?

Not directly - but this has nothing to do with a reference-or-value
problem. It's just that floats (like ints, strings and tuples) are
immutable. You'll need either to work with indices or to wrap your
floats in mutable objects. I'd recommand the first solution.

> Greets to all PyFans
> zefciu


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list