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

boB Stepp robertvstepp at gmail.com
Thu Oct 18 05:41:39 CEST 2012


>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.
These two objects just happen to have the same value, ["Retention", 3,
None], stored in two separate locations. a and b, the object
references (Variables are what I used to call these.), store these two
separate memory locations. Thus a is b is false. However, when the
line b = a is implemented, b now references the same object (memory
location) as a, which now causes a is b to be true. Is my
understanding correct?

On the next page the author states (after giving a string example
where a and b each are assigned the string "many paths", similar to
the example above):

"In some cases, comparing the identity of two strings or numbers--for
example, using a is b--will return True, even if each has been
assigned separately as we did here. This is because some
implementations of Python will reuse the same object (since the value
is the same and is immutable) for the sake of efficiency..."

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?

-- 
Thanks!
boB


More information about the Tutor mailing list