This text is part of a Real Python tutorial by Joska de Langen.
You can also watch the related Real Python video course by Liam Pulsifer: Comparing Python Objects the Right Way: “is” vs “==”
There’s a subtle difference between the Python identity operator (is
) and the equality operator (==
). Your code can run fine when you use the Python is
operator to compare numbers, until it suddenly doesn’t. You might have heard somewhere that the Python is
operator is faster than the ==
operator, or you may feel that it looks more Pythonic. However, it’s crucial to keep in mind that these operators don’t behave quite the same.
The ==
operator compares the value or equality of two objects, whereas the Python is
operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators ==
and !=
, except when you’re comparing to None
.
In this lesson, you’ll learn:
- What the difference is between object equality and identity
- When to use equality and identity operators to compare objects
- What these Python operators do under the hood
- Why using
is
andis not
to compare values leads to unexpected behavior - How to write a custom
__eq__()
class method to define equality operator behavior
Comparing Identity With the Python is and is not Operators
The Python is
and is not
operators compare the identity of two objects. In CPython, this is their memory address. Everything in Python is an object, and each object is stored at a specific memory location. The Python is
and is not
operators check whether two variables refer to the same object in memory.
Note: Keep in mind that objects with the same value are usually stored at separate memory addresses.
You can use id()
to check the identity of an object:
>>> help(id)
Help on built-in function id in module builtins:
id(obj, /)
Return the identity of an object.
This is guaranteed to be unique among simultaneously existing objects.
(CPython uses the object's memory address.)
>>> id(id)
2570892442576
The last line shows the memory address where the built-in function id
itself is stored.