Search code examples
pythonlow-level

Unexpected id method behaviour


In simple terms, why this code returns False and not true:

a = 10
print(id(a) is id(a)) # why false?

id() returns integer, and same integer vars point to the same integer object. Why it returns false then? What is the difference with:

a = 10
b = 10
print(a is b) # it returns True

Thanks for explanation.


Solution

  • Because, while it is true that

    a is a
    

    id(a) is a large integer and does not compare by is

    >>> a = 10
    >>> print(id(a) is id(a))
    False
    >>> print(id(a),id(a))
    (44337068, 44337068)
    >>>
    

    Check https://docs.python.org/2/c-api/int.html#c.PyInt_FromLong for which integers compare by is - but remember that is an implementation detail so don't rely on it (always compare ints with ==):

    >>> a = 256
    >>> b = 256
    >>> a is b
    True
    >>> a = 257
    >>> b = 257
    >>> a is b
    False
    

    (from "is" operator behaves unexpectedly with integers)

    For further motivation to always use ==, the following:

    a = 300
    b = 300
    print(a is b)
    print(a is 300)
    def c(a): return a is 300
    def d(a): return a is b
    print(c(a))
    print(d(a))
    

    when saved to a file and run, prints True, True, False, and True...