id == vs is

Joshua Landau joshua at
Mon Oct 27 01:20:01 CET 2014

On 27 October 2014 00:12, Dan Stromberg <drsalists at> wrote:
> Are the following two expressions the same?
> x is y
> Id(x) == id(y)

Much of the time, but not all the time. The obvious exception is if
"id" is redefined, but that one's kind of boring. The real thing to
watch out for is if the object that "x" points to is garbage collected
before "y" is evaluated:

   nothing = "!"

    id("hello" + nothing) == id("hello" + nothing)
    #>>> True

    ("hello" + nothing) is ("hello" + nothing)
    #>>> False

Since in the first case the ("hello" + nothing) gets garbage
collected, CPython is allowed to re-use its id. If instead you assign
them outside of the expression:

    nothing = "!"

    x = "hello" + nothing
    y = "hello" + nothing
    id(x) == id(y)
    #>>> False

the collection cannot happen.

Note that in this case CPython is allowed to deduplicate these strings
anyway (although in this case it does not), so using "is" here is not

More information about the Python-list mailing list