Python Comparison Operators

Filed Under: Python

Python Comparison Operators are used to compare two objects. The output returned is a boolean value – True or False.

Python Comparison Operators

There are 6 types of comparison operators in Python.

Comparison Operator Description Example
== returns True if two operands are equal, otherwise False. a == b
!= returns True if two operands are not equal, otherwise False. a != b
> returns True if left operand is greater than the right operand, otherwise False. a > b
< returns True if left operand is smaller than the right operand, otherwise False. a < b
>= returns True if left operand is greater than or equal to the right operand, otherwise False. a > b
<= returns True if left operand is smaller than or equal to the right operand, otherwise False. a < b

Python Comparison Operators Example

Let’s look at a simple example of using comparison operators with primitive data type such as an integer.


>>> a = 10
>>> b = 10
>>> c = 20
>>> 
>>> a == b
True
>>> a != b
False
>>> c > a
True
>>> c < a
False
>>> c <= 20
True
>>> c >= 20
True
>>>
Python Comparison Operator Integer

Python Comparison Operator – Integer

Python Comparison Operators with String

The string is an object in Python programming. Let’s see whether comparison operators work with Strings or not.


>>> # string comparison
>>> s1 = 'a'
>>> s2 = 'a'
>>> s3 = 'b'
>>> s1 == s2
True
>>> s1 != s2
False
>>> s1 > s3
False
>>> s1 < s3
True
>>> s1 <= s2
True
>>> s1 >= s2
True
>>> 
Python Comparison Operator String

Python Comparison Operators – String

So does it mean that comparison operators will work with any python objects?

Let’s check it out by creating a custom class.


>>> class Data:
	pass

>>> d1 = Data()
>>> d2 = Data()
>>> d1 == d2
False
>>> d1 != d2
True
>>> d1 > d2
Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
    d1 > d2
TypeError: '>' not supported between instances of 'Data' and 'Data'
>>> d1 < d2
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    d1 < d2
TypeError: '<' not supported between instances of 'Data' and 'Data'
>>> d1 <= d2
Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    d1 <= d2
TypeError: '<=' not supported between instances of 'Data' and 'Data'
>>> d1 >= d2
Traceback (most recent call last):
  File "<pyshell#33>", line 1, in <module>
    d1 >= d2
TypeError: '>=' not supported between instances of 'Data' and 'Data'
>>> 
>>> 
Python Comparison Operator Overloading Error

Python Comparison Operator Overloading Error

Why equals and not-equals operator worked but others didn’t?

It’s because “object” is the base of every class in Python. And object provides an implementation of functions that are used for equals and not-equals operator.

Functions for Comparison Operators

Here is the list of functions that are used by comparison operators. So if you want comparison operators to work with the custom object, you need to provide an implementation for them.

Comparison Operator Function
== __eq__(self, other)
!= __ne__(self, other)
> __gt__(self, other)
< __lt__(self, other)
>= __ge__(self, other)
<= __le__(self, other)

Python Comparison Operators Overloading

Let’s look at an example to overload comparison operators in a custom object.


# Learn how to override comparison operators for custom objects


class Data:
    id = 0

    def __init__(self, i):
        self.id = i

    def __eq__(self, other):
        print('== operator overloaded')
        if isinstance(other, Data):
            return True if self.id == other.id else False
        else:
            return False

    def __ne__(self, other):
        print('!= operator overloaded')
        if isinstance(other, Data):
            return True if self.id != other.id else False
        else:
            return False

    def __gt__(self, other):
        print('> operator overloaded')
        if isinstance(other, Data):
            return True if self.id > other.id else False
        else:
            return False

    def __lt__(self, other):
        print('< operator overloaded')
        if isinstance(other, Data):
            return True if self.id < other.id else False
        else:
            return False

    def __le__(self, other):
        print('<= operator overloaded')
        if isinstance(other, Data):
            return True if self.id <= other.id else False
        else:
            return False

    def __ge__(self, other):
        print('>= operator overloaded')
        if isinstance(other, Data):
            return True if self.id >= other.id else False
        else:
            return False


d1 = Data(10)
d2 = Data(7)

print(f'd1 == d2 = {d1 == d2}')
print(f'd1 != d2 = {d1 != d2}')
print(f'd1 > d2 = {d1 > d2}')
print(f'd1 < d2 = {d1 < d2}')
print(f'd1 <= d2 = {d1 <= d2}')
print(f'd1 >= d2 = {d1 >= d2}')

Output:


== operator overloaded
d1 == d2 = False
!= operator overloaded
d1 != d2 = True
> operator overloaded
d1 > d2 = True
< operator overloaded
d1 < d2 = False
<= operator overloaded
d1 <= d2 = False
>= operator overloaded
d1 >= d2 = True

Summary

Python comparison operators are used to compare two objects. We can easily implement specific functions to provide support for these operators for our custom objects.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages