[Tutor] is gotchas?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Nov 7 03:24:43 CET 2006

>>>> c='1'  ## one byte
>>>> d='1'  ## one byte
>>>> c is d
> True
>>>> c='1,2'
>>>> d='1,2'
>>>> c is d
> False
> The Hmmm! is emmitted because I'm thinking that if everything is an
> object in python, then why does `c is d` evaluate to True when
> the assigned value is 1 byte and evaluate to False when the assigned
> value is more that 1 byte?

'is' is the operator you want if you want to check for object identity. 
You should probably not use it for strings, or for immutables for that 
matter.  Its value here is "undefined" above in the sense that our 
programs shouldn't depend on the behavior you're seeing there.

(And you'll see different behavior depending on if Python is being run as 
an interpreter vs. on a whole program.  On a whole program, all the 
duplicate string literals tend to be shared since Python strings are 

A closer look at:


is helpful, especially near the bottom.

'is' is relatively rare; I've seen it used most often in code dealing with 
object caches.

More information about the Tutor mailing list