Understanding the “is” operator [duplicate]

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)
>>> id(y)

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

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

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.

Leave a Comment