Python '!=' Is Not 'is not': Comparing Objects in Python (Overview)
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 course, 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
00:00
Hi there, and welcome to this Real Python video course on Python comparison operators. In this course, you’ll learn how to use the two forms—or two of the forms—of Python’s comparison operators: the is
and its counterpart is not
operator, which compare object identity, and the double equals (==
) and not equals (!=
) operators, which compare object equality.
00:25
I’ll also go through the difference between those two concepts, object equality and identity, when to use the two different forms of operators to compare objects and what these operators do under the hood. I’ll explain why is
and is not
for value comparison—and I’ll get into, of course, what that means precisely—why that comparison leads to unexpected behavior.
00:47
And then finally, I’ll really get into the guts of how these operators work and what they do under the hood, and in the process of doing that, I’ll show you how to write a custom .__eq__()
(equals) class method to define how the equality operator behaves.
Become a Member to join the conversation.