Result of ``a is b''

Skip Montanaro skip at pobox.com
Mon Mar 15 19:56:27 EST 2004


    Axel> is there a rationale for the following behavior:

    >>> a = (1,2)
    >>> b = (1,2)
    >>> a is b
    False
    >>> a = "12"
    >>> b = "12"
    >>> a is b
    True

Sure.  The "is" operator doesn't do an element-by-element comparison of the
two objects.  It only compares the memory addresses of the two objects being
compared.  The difference between the tuple case and the string case is that
string literals which look roughly like identifiers (no spaces, all letters,
digits or underscores) are automatically interned and are thus shared.  As
Andrew Koenig indicated, it's an implementation detail.  It improves
performance to intern identifiers and it's not worth the extra expense to
decide if a string literal is really being used as a variable name, so all
strings which look structurally like identifiers are interned.  You should
generally only use "is" to compare objects against known singleton objects:
None, True, False and Ellipsis.  Use "==" for everything else.

Skip




More information about the Python-list mailing list