string identity and comparison

Peter Otten __peter__ at web.de
Thu Dec 16 07:50:45 EST 2010


Steve Holden wrote:

> On 12/16/2010 6:55 AM, Jean-Michel Pichavant wrote:
>> Fellows,
>> 
>> I'd like to illutrate the fact that comparing strings using identity is,
>> most of the time, a bad idea. However I'm searching a short example of
>> code that yields 2 differents object for the same string content.
>> 
>> id('foo')
>> 3082385472L
>> id('foo')
>> 3082385472L
>> 
>> Anyone has that kind of code ?
>> 
>> JM
>> 
>>>> id("foo")
> 2146743808
>>>> id ("f"+"o"+"o")
> 2146744096

Note that the concatenation may be misleading because it's not the direct 
reason that the ids differ; the first string doesn't exist anymore when the 
second is built, but the memory location of the first "foo" is occupied 
(perhaps by an intermediate string) when the second "foo" is created. To 
illustrate:

>>> id("foo")
140394722220912
>>> id("bar")
140394722220912

>>> id("foo")
140394722220912
>>> x = 1234
>>> id("foo")
140394722221008




More information about the Python-list mailing list