Understanding Python's “is” operator

前端 未结 11 2424
别那么骄傲
别那么骄傲 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:16

    You misunderstood what the is operator tests. It tests if two variables point the same object, not if two variables have the same value.

    From the documentation for the is operator:

    The operators is and is not test for object identity: x is y is true if and only if x and y are the same object.

    Use the == operator instead:

    print(x == y)
    

    This prints True. x and y are two separate lists:

    x[0] = 4
    print(y)  # prints [1, 2, 3]
    print(x == y)   # prints False
    

    If you use the id() function you'll see that x and y have different identifiers:

    >>> id(x)
    4401064560
    >>> id(y)
    4401098192
    

    but if you were to assign y to x then both point to the same object:

    >>> x = y
    >>> id(x)
    4401064560
    >>> id(y)
    4401064560
    >>> x is y
    True
    

    and is shows both are the same object, it returns True.

    Remember that in Python, names are just labels referencing values; you can have multiple names point to the same object. is tells you if two names point to one and the same object. == tells you if two names refer to objects that have the same value.

提交回复
热议问题