String Identity Test

Magnus Lycka lycka at carmen.se
Tue Nov 1 09:09:34 EST 2005


Thomas Moore wrote:
>>>>a="test"
>>>>b="test"
>>>>a is b
> 
> True
> 
> About identity, I think a is not b, but "a is b" returns True.
> Does that mean equality and identity is the same thing for strings?

Not exactly:

>>> a="this is also a string"
>>> b="this is also a string"
>>> a is b
False

It's the same with integers. Small ones are shared, big ones aren't.
Details vary with Python version.

Python sometimes optimizes its memory use by reusing immutable objects.
If you've done 'a="test"', and does 'b="test"', Python sees that it can
save some memory here, so instead of creating a new string object on the
heap (which is what happened when you did 'a="test"'), it makes 'b'
refer to that already existing "test" string object that 'a' refers to.
It's roughly as if you would have written 'b=a' instead.

Of course, it would *never* do this for mutable objects.
'a=[];b=[];a.append(1)' must leave b empty, otherwise Python would be
seriously broken. For immutable objects, this isn't a problem though.
Once created, the 'test' string object will always be the same until
it's destroyed by garbage collection etc.

Were you planning to write code that relied on id(x) being different
for different but identical strings x or do you just try to understand
what's going on?



More information about the Python-list mailing list