string identity and comparison

André andre.roberge at gmail.com
Thu Dec 16 07:07:06 EST 2010


On Thursday, December 16, 2010 7:55:20 AM UTC-4, jeanmichel 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

How about this:

Python 2.6 (trunk:66714:66715M, Oct  1 2008, 18:36:04) 
[GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 'spam'
>>> b = 'spa'
>>> c = a[:-1]
>>> c
'spa'
>>> id(c)
548256
>>> id(b)
548224

Or, even more simply, this:

Jython 2.5.0 (Release_2_5_0:6476, Jun 16 2009, 13:33:26) 
[Java HotSpot(TM) Client VM (Apple Inc.)] on java1.5.0_26
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 'foo'
>>> b = 'foo'
>>> id(a)
1
>>> id(b)
2

Reusing immutable objects, for the sake of efficiency, is an implementation details which should not be relied upon (as you know since you ask for examples).

André



More information about the Python-list mailing list