Problem with objects copying each other in memory

Rhodri James rhodri at wildebst.demon.co.uk
Thu Feb 12 19:51:10 EST 2009


On Thu, 12 Feb 2009 22:29:29 -0000, Cameron Pulsford  
<cameron.pulsford at gmail.com> wrote:

> Thanks, that did it! Why is that the case though? Or rather, why do the  
> assignments to temp.x and temp.y not effect the self.x and self.y? How  
> come I only run into the problem with the list?

Variable names and assignment don't work the same way in Python as they
do in C (say).  What assignment does is to attach the name on the left
to the object on the right.  Obviously this is oversimplifying, since
"the name on the left" could be a list or dictionary element or the like,
but the principle holds: variables aren't objects themselves, they're
just references to objects.

For your ordinary everyday integers, this is arranged to be no different
 from normal.  Suppose we have

     x = 5
     y = x
     x = x + 1
     print y

Then we start by creating an integer object with the value 5 and labelling
it "x".  Then we pick up that object and label it 'y' as well.  The next
line causes us to create an integer object with the value 1, pick up the
object we called 'x', and tell that object to add the '1' object to itself.
That results in creating a brand new object (with the value 6), which we
then label 'x'.  The original '5' object (still labelled 'y') hasn't been
changed by this, because Python does arithmetic by creating new integer
objects.

Lists operate the same way for concatenation and repetition.

    a = [1, 2, 3]
    b = [4, 5, 6]
    c = a
    a = a + b
    print c

The "a = a + b" line creates a new list consisting of the elements of
the old list 'a' followed by the elements of the old list 'b', without
changing either of those lists in the slightest, and then calls this
new list 'a'.  The old list is still hanging around, and still has the
label 'c' attached to it.

The differences from your expectations arise because lists are mutable,
and integers aren't.  In other words we can change the contents of a
list "in place" without creating a new list.

     a = [1, 2, 3]
     b = a
     a.append(4)
     print b

Here, the list has both labels 'a' and 'b' attached to it.  When we
call a.append, it doesn't create a new list or anything like that,
it just makes the existing list larger and tacks the new value on
the end.  Because it's still the same list as before, it's still
got both names attached to it, so when you print 'b' out you see
the changed list [1, 2, 3, 4].

-- 
Rhodri James *-* Wildebeeste Herder to the Masses



More information about the Python-list mailing list