Comparing Objects

Here, you'll learn how to compare different objects with one another in Python

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 and b, are equal if every part of a is the same as the corresponding part of b. If you change a, b might or might not change. Testing for equality requires testing all the parts.

  • However, if a and b are identical then they are just two different names for the same object. Changing that object by doing something to a means that b also undergoes the change. Testing for identity just involves testing whether a and b 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 object b. It only makes a refer to the same object as b.

  • 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 whether a and b 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 return True if you consider the self objects and other to be equal and False otherwise. Identical objects should be considered to be equal (you can test identity with the is 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 1400+ tech skills courses.