[Tutor] Objects, object references, object values and memory addresses

Alan Gauld alan.gauld at btinternet.com
Thu Oct 18 09:32:41 CEST 2012


On 18/10/12 04:41, boB Stepp wrote:
>  From Programming in Python 3, 2nd edition (p. 22-23):
>
>>>> a = ["Retention", 3, None]
>>>> b = ["Retention", 3, None]
>>>> a is b
> False
>>>> b = a
>>>> a is b
> True
>
> My current understanding is as follows: On the first two lines, two
> separate objects are defined, stored in two separate blocks of memory.

Two separate list objects are created. In Python it is rarely helpful to 
think about memory usage. Python is abstracted so far from the physical 
machine that the connection usually depends on the creator of the 
interpreter rather than the language.

> These two objects just happen to have the same value, ["Retention", 3,
> None], stored in two separate locations.

Yes, but note that its the fact that they are two separate lists that 
matters. Even if the contents were the same objects they would still be 
two lists:

 >>> x = [42]
 >>> y = 'spam'
 >>> z = None
 >>> a = [x,y,z]
 >>> b = [x,y,z]   # different list, exact same content
 >>> a is b
False
 >>> a == b
True
 >>> a = b
 >>> a is b
True
 >>> a == b
True
 >>>

 > a and b, object references (Variables are what I used to call these.

And most folks still do...

> I ask: Which implementations of Python do this? In trying to make any
> code I write portable across as many platforms as possible, should I
> avoid using the identity operator, is (and its opposite, is not),
> except when I wish to compare to None?

The point is that you don't know. And, even if you did, the very next 
release might change it so you cannot rely on it. That's the real 
message - do not assume a particular implementation technique because it 
is not guaranteed to be that way or to stay that way.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list