Search code examples
pythonoperators

Understanding the "is" operator


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

What does it really mean?

I declared two variables named x and y assigning the same values in both variables, but it returns false when I use the is operator.

I need a clarification. Here is my code:

x = [1, 2, 3]
y = [1, 2, 3]

print(x is y)  # False

Solution

  • 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.