id(a) == id(b) and a is not b --> bug?

Duncan Booth duncan at
Fri Jun 6 16:27:47 CEST 2003

Steve McAllister <nosp at m.needed> wrote in news:bbq5df$9nm$1 at alto.univ-

> And exactly why is {
> 'foo' is 'foo' is 'foo' is 'foo'
> } always true?  This is quite surprising compared to {
> [] is []
> } ...
> Why are not new string literals dynamically created?

String literals are immutable. If an object is immutable there is no 
benefit to creating a new one each time, so the compiler may decide just to 
reuse an existing object.

The rules for when the compiler creates a new object or just reuses an 
existing one are complex and vary with different versions of Python, so the 
only things you can safely depend on are:

 if two immutable objects are the same, they could have the same id.
 if two objects are different and have overlapping lifetimes they cannot 
have the same id.

In particular here is an example of a situation where the actual contents 
of the string determine whether a new string is created or one is reused: 

>>> a = 'foo'
>>> a is 'foo'
>>> a = 'foo bar'
>>> a is 'foo bar'

Duncan Booth                                             duncan at
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?

More information about the Python-list mailing list