Understanding Python's “is” operator

前端 未结 11 2302
别那么骄傲
别那么骄傲 2020-11-21 22:42

The is operator does not match the values of the variables, but the instances themselves.

What does it really mean?

11条回答
  •  面向向阳花
    2020-11-21 23:08

    is and is not are the two identity operators in Python. is operator does not compare the values of the variables, but compares the identities of the variables. Consider this:

    >>> a = [1,2,3]
    >>> b = [1,2,3]
    >>> hex(id(a))
    '0x1079b1440'
    >>> hex(id(b))
    '0x107960878'
    >>> a is b
    False
    >>> a == b
    True
    >>>
    

    The above example shows you that the identity (can also be the memory address in Cpython) is different for both a and b (even though their values are the same). That is why when you say a is b it returns false due to the mismatch in the identities of both the operands. However when you say a == b, it returns true because the == operation only verifies if both the operands have the same value assigned to them.

    Interesting example (for the extra grade):

    >>> del a
    >>> del b
    >>> a = 132
    >>> b = 132
    >>> hex(id(a))
    '0x7faa2b609738'
    >>> hex(id(b))
    '0x7faa2b609738'
    >>> a is b
    True
    >>> a == b
    True
    >>>
    

    In the above example, even though a and b are two different variables, a is b returned True. This is because the type of a is int which is an immutable object. So python (I guess to save memory) allocated the same object to b when it was created with the same value. So in this case, the identities of the variables matched and a is b turned out to be True.

    This will apply for all immutable objects:

    >>> del a
    >>> del b
    >>> a = "asd"
    >>> b = "asd"
    >>> hex(id(a))
    '0x1079b05a8'
    >>> hex(id(b))
    '0x1079b05a8'
    >>> a is b
    True
    >>> a == b
    True
    >>>
    

    Hope that helps.

提交回复
热议问题