Problem with objects copying each other in memory

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Fri Feb 13 10:10:34 CET 2009

Cameron Pulsford a écrit :

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

Because there's a huge difference between binding an object to a name 
and mutating an object ?

First point: Python's "assignment"  is really a binding of a name and an 
object _reference_ in a given namespace. Think of namespaces as 
name=>object_ref dictionnaries. This implies that "assignement" never 
copies anything. So when you do:

 >>> list1 = []
 >>> list2 = list1

the second line actually creates *another* name=>object pair referencing 
the *same* list object. IOW, list1 and list2 are two named references to 
a single object:

  >>> list1 is list2
 >>> id(list1) == id(list2)

So whether you access it thru name 'list1' or 'list2', if you mutate the 
object (like append/remove/replace an element of the list), you'll see 
the result thru the other name as well:

 >>> list1.append('foo')
 >>> list2.append('bar')
 >>> list1
['foo', 'bar']
 >>> list2
['foo', 'bar']

Note FWIW that list subscripting (somelist[x] = y) is really a method 
call (somelist.__setitem__(x, y)) in disguise, so the same reasonning 

Now *rebinding* a name is a different thing. It makes the name refer to 
another object, but has no impact on other name=>object bindings 
refering to the previously bound object, ie:

 >>> list2 = ['hou', 'lala']

Now list2 points to a newly created list object. This doesn't impact 
list1 of course:

 >>> list1
['foo', 'bar']
 >>> list1 is list2
 >>> id(list1) == id(list2)


More information about the Python-list mailing list