Comparing Objects
Here, you'll learn how to compare different objects with one another in Python
We'll cover the following
Comparing objects in Python
The equality (==
) and inequality (!=
) operators work well with Python’s built-in object types. However, when you define your own classes, ==
will always return False
when comparing two objects.
When we talk about drawing comparison between two objects, it is important to keep in mind the distinction between equal and identical.
-
Two objects,
a
andb
, are equal if every part ofa
is the same as the corresponding part ofb
. If you changea
,b
might or might not change. Testing for equality requires testing all the parts. -
However, if
a
andb
are identical then they are just two different names for the same object. Changing that object by doing something toa
means thatb
also undergoes the change. Testing for identity just involves testing whethera
andb
both refer to the same location in memory.
When comparing objects in Python, keep in mind the following points:
-
The assignment
a = b
never makes a copy of an objectb
. It only makesa
refer to the same object asb
. -
When you use an object as an argument to a function, the function gets a reference to the original object, not a copy.
-
a is b
tests whethera
andb
refer to the same object.a is not b
tests whether they are different (but possibly equal) objects.
Built-in equality class methods
For your own class, you can easily define equality and ordering by defining some special methods in the class, which you can find below:
Note: All these names use double underscores.
-
__eq__(self, other)
should returnTrue
if you consider theself objects
andother
to be equal andFalse
otherwise. Identical objects should be considered to be equal (you can test identity with theis
operator). This method will be called when your objects are compared using==
. -
__ne__(self, other)
will be called when objects are compared using!=
. -
__lt__(self, other)
will be called when objects are compared using<
. -
__le__(self, other)
will be called when objects are compared using<=
. -
__ge__(self, other)
will be called when objects are compared using>=
. -
__gt__(self, other)
will be called when objects are compared using>
.
These methods are all independent. Defining some of them does not automatically define others. For example, if you define an __eq__
method, __ne__
does not magically pop into being. If you wish to use any of the comparison operators (==
, !
=
, etc.) for your objects, you must define the corresponding method. If you don’t, you will get the default behavior for the operators, which will almost certainly be incorrect.
The following examples makes use of these operators:
Get hands-on with 1200+ tech skills courses.