[Pythonmac-SIG] string ids

Ronald Oussoren ronaldoussoren at mac.com
Mon Dec 29 16:57:24 CET 2008


Do not rely on the id of instances of builtin types of Python. The "is" operator is used to determine if two expressions refer to the same object, use the "==" operator to determine if two expressions have the same value.

For some builtin value types the interpreter always uses the same Python object for the same value, for other types it does not. That's purely an implementation detail, future versions of Python may behave differently in this respect.  That's the explanation for the behaviour you're seeing. When you execute this code:

:>>> x = 'blue'
:>>> y = 'bl' + 'ue'
:>>> a = 1
:>>> b = 2/2

"x" and "y" refer to two different string objects with the value 'blue'. "a" and "b" refer to the same integer object with value 1, which is due to the optimisation I mentioned earlier. This is not true for arbitrary objects though:

:>>> c = 2 ** 12
:>>> d = 2 ** 12
:>>> c is d
False

Ronald
 
On Monday, December 29, 2008, at 04:31PM, "Sean DiZazzo" <half.italian at gmail.com> wrote:
>Interesting... It behaves correctly for strings if you use a list inside the
>comprehension instead of a tuple.
>~Sean
>
>On Mon, Dec 29, 2008 at 7:01 AM, Feat <jf at ai.univ-paris8.fr> wrote:
>
>> I thought a string was stored as a unique object, so why isn't this
>> evidenced by the code below ?
>>
>>        Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53)
>>        [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
>>        >>> [light is 'green' for light in 'green', 'red']
>>        [True, False]
>>        >>> color = 'green'
>>        >>> [light is 'green' for light in 'green', 'red']
>>        [False, False]
>>        >>> color = 1
>>        >>> [light is 'green' for light in 'green', 'red']
>>        [True, False]
>>
>> whereas:
>>
>>        >>> [x is 1 for x in 1, 2]
>>        [True, False]
>>
>> whether the value 1 is assigned to some other variable or not... the id of
>> 1 doesn't vary -- just what is the rationale behind that?
>>
>> I know I could use the == predicate instead, but just how many different
>> greens (with different ids) can  there be, and how do I know which one is
>> under focus at a given time?
>>
>> --
>> Jym Feat ~ Paris FR 75018
>> _______________________________________________
>> Pythonmac-SIG maillist  -  Pythonmac-SIG at python.org
>> http://mail.python.org/mailman/listinfo/pythonmac-sig
>>
>


More information about the Pythonmac-SIG mailing list