Comparison Operators in Python
FREE Online Courses: Transform Your Career – Enroll for Free!
You would have come across many operators like addition, subtraction, greater than, etc. in Mathematics. You would have come across it even in day-to-day life like comparing prices of two things. Some of such operators are Comparison Operators.
We will learn about different operators that come under this category of operators in this article. So, let us not wait and begin.
Introduction to Comparison Operators
Comparison operators are the operators that compare the values on either side of the symbol. Depending on their operation, these checks if the two operands satisfy the given condition. Then return either “True” or “False” based on the result. Thus, these are also called relational operators.
In Python, there are six types of comparison operators:
1. Less than (<)
2. Greater than (>)
3. Less than or equal to (<=)
4. Greater than or equal to (>=)
5. Equal to (==)
6. Not equal to (!=)
We will learn about each of the operators in the following sections.
1. Less than Operator (<) in Python
Less than Operator checks if the left operand is less than the right operand or not. Based on this it outputs either “True” or “False”. Let us see an example.
Example of less than operator:
3<19
Output:
Since 3 is less than 19, it gave True.
Example on less than operator:
10<5
Output:
10 is greater than 5, so the result is False
Examples on less than operator:
6<6
Output:
6 is not less than 6, so the output is False.
We can perform this operation not only on integers. Let us see different cases where it can be used:
a. Comparing int and float: We can compare an integer and a float and we get normal results. Look at the below code blocks
Examples of using < operator on int and float:
5<5.0
Output:
The output is False because the values 5 and 5.0 are equal, the decimal point is not considered as it is zero.
Examples of using < operator on int and float:
5.6<6
Output:
The output is True because the value of 5.5 is less than 6, here while comparison 6 can be considered as 6.0.
b. Comparing two strings: We can use this operator to compare two strings. The comparison is done by converting the letters to ASCII code and checking the letters from the left-hand side.
Examples on comparing strings using <:
"PythonGeeks"<"pythongeeks"
Output:
The output is “True” because the ASCII value of “P” is 60 and “p” is 70. Since the 1st letters mismatch and P<p, the output is True.
c. Containers like tuples: This operator can be used for comparing containers. To get more understanding look at the below examples.
Example of < operator on tuples:
(4,3,7)<(4,5,6)
Output:
The first elements are the same but the 2nd element of the left tuple is less than that of the right tuple. So, it does not check further and gives True.
Example of < operator on tuples:
(9,5,6)<(9,5,6,8)
Output:
Though the first three elements are the same, the right tuple has an extra element. So, the output is True.
Example of < on tuples with different data types:
(1,3)<("Python","Geeks")
Output:
File “<pyshell#10>”, line 1, in <module>
(1,3)<(“Python”,”Geeks”)
TypeError: ‘<‘ not supported between instances of ‘int’ and ‘str’
This gave an error because the elements of the tuple are of different data types and comparison is not possible. However, a comparison can be done if the corresponding elements are of the same data type. For example,
Example of < on tuple with corresponding elements having same data type:
("Python",4.0)<("Geeks",2.5)
Output
This gives false as “P” in “Python” has a greater ASCII value than the first letter “G” in “Geeks”. We will get an error if the elements are switched in one of the tuples. For example, see the below example. Both the tuples have str and int data type elements, but their order is not the same, so we get an error
Example of < on tuples with different data types:
(3,"Python")<("Geeks",19)
Output:
File “<pyshell#12>”, line 1, in <module>
(3,”Python”)<(“Geeks”,19)
TypeError: ‘<‘ not supported between instances of ‘int’ and ‘str’
Example on applying < on lists:
[5,6]<[7,8]
Output:
5 is less than 7. So, the output is True.
Example of applying < on sets:
{4,5,7}<{7,4,5,}
Output:
This gives False because the elements of the set rearrange to ascending order and therefore both sets will be equal.
d. For dictionaries: This operator cannot be applied for dictionaries, even if data types match. The reason for this is that the dictionary elements are not ordered. We know that comparison operators like < stop when they reach an unequal value and give the result. And we cannot know the order of comparison of the elements and thus it is not supported by dictionaries.
The code below displays that.
Example of using < for dictionaries giving an error:
{1:"a",2:"b"}<{19:"p",20:"t"}
Output:
File “<pyshell#16>”, line 1, in <module>
{1:”a”,2:”b”}<{19:”p”,20:”t”}
TypeError: ‘<‘ not supported between instances of ‘dict’ and ‘dict’
2. Greater than Operator (>) in Python
This operator checks if the left operand is greater than the right operand. And outputs “True” if it is else “False”. Let us see an example.
Examples of > Operator:
19>15
Output:
Since 19 is greater than 15 it gives output as “True”. But 35 is less than 50. So, the below code returns “False”.
Examples of > Operator:
35>50
Output:
Since 35 is less than 50, the result is False.
Similar to the less-than operator, this can be applied for strings and containers.
Example of applying > operator on strings and tuples:
(34,6,4)>(21,15,30) "Python">"python"
Output:
False
Since 34 is greater than 21, this gives True. Since the ASCII value of “P” is less than that of “p”, the result is False.
But look at the following result.
Example of applying > operator giving a tuple:
"a",4,6,5>7,9.0
Output:
This gives a tuple because comparison is done only between 5 and 7 and the result is False. This occurred due to the absence of brackets to represent it as a collection. However, the brackets have to be on either side, else we get an error.
3. Less than or Equal to Operator (<=) in Python
This operator checks if the left value is less than or equal to the right value and gives the appropriate result as True or False. The following examples illustrate this.
Examples on <= operator:
39<=34
Output:
Since 39 is greater than 34, it gave False.
Examples on <= operator:
25<=25
Output:
Since 25 is equal to 25, the result is True. This operator can also be applied in a similar way to Strings and containers.
4. Greater than or Equal to Operator (>=) in Python
This checks if the left value is greater than or equal to the right value and gives the appropriate result as True if correct or else False. For example,
Examples on >= operator:
29>=47
Output:
Since 29 is less than 47, it gave False.
Examples on >= operator:
18>=18
Output:
Since 18 is equal to 18, the output is True. You can compare strings and containers similarly using this operator.
5. Equal to Operator (==) in Python
This operator checks if the left value and the right value are equal or not and gives the respective result as True or False. The following examples show this.
Examples on == operator:
13==31
Output:
Since 13 is less than 31, the result is False.s
Examples on == operator:
3==3.0
Output:
Since 3 is equal to 3, even though the data type is not the same, the value is the same on the decimal side also. So the result is True. This operator can also be applied in a similar way to Strings and containers, including dictionaries.
6. Not equal to Operator (!=) in Python
This operator checks if the left value is not equal to the right value and gives the appropriate result as True or False. This works in the opposite way to equal to operator Look at the below examples.
Examples on != operator:
26 !=54
Output:
Since 26 is less than 54, it gave True.
Examples on != operator:
3.5!=3.5
Output:
Since 3.5 is equal to 3.5, the result is False. This operator can be similarly applied to Strings and containers, including dictionaries.
Overloading Comparison Operator in Python
Operator Overloading is a method of giving extra functionality to an operator, in addition to its predefined one. An example of it is the ‘+’ operator applied on integers and strings. When we use it on integers, it adds numbers in the same way as in maths. When we use the same ‘+ operator on strings, it concatenates them. So, the ‘+’ behaves in a different way with different data types/classes, and the operator is said to be overloaded.
We can overload comparison operators too, by creating a magic function, starting and ending with double underscores. It gets invoked whenever the associated operator is called. For the comparison operators, the magic functions are listed in the below table.
Comparison operator | Function |
< | __lt__(self,obj) |
> | __gt__(self,obj) |
<= | __le__(self,obj) |
>= | __ge__(self,obj) |
== | __eq__(self,obj) |
!= | __ne__(self,obj) |
Example of overloading comparison operators:
class ComparisonOverload(): #creating a class def __init__(self,val): #defining init function self.val=val def __gt__(self,obj): #overloading > operator print("Overloading > operator") if isinstance(obj,ComparisonOverload): #checking if the object is defined in the class return True if self.val > obj.val else False #doing > operation on values of both the objects else: raise ValueError #if not defined in the class showing an error def __lt__(self,obj): #overloading < operator print("Overloading < operator") if isinstance(obj,ComparisonOverload): #checking if the object is defined in the class return True if self.val < obj.val else False #doing < operation on values of both the objects else: raise ValueError #if not defined in the class showing an error def __eq__(self,obj): #overloading == operator print("Overloading == operator") if isinstance(obj,ComparisonOverload): #checking if the object is defined in the class return True if self.val == obj.val else False #doing == operation on values of both the objects else: raise ValueError #if not defined in the class showing an error def __ne__(self,obj): #overloading != operator print("Overloading != operator") if isinstance(obj,ComparisonOverload): #checking if the object is defined in the class return True if self.val != obj.val else False #doing != operation on values of both the objects else: raise ValueError #if not defined in the class showing an error def __le__ (self,obj): #overloading <= operator print("Overloading <= operator") if isinstance(obj,ComparisonOverload): #checking if the object is defined in the class return True if self.val <= obj.val else False #doing <= operation on value by the value of the object else: raise ValueError #if not defined in the class showing an error def __ge__ (self,obj): #overloading >= operator print("Overloading >= operator") if isinstance(obj,ComparisonOverload): #checking if the object is defined in the class return True if self.val >= obj.val else False #doing >= operation on value by the value of the object else: raise ValueError #if not defined in the class showing an error if __name__=='__main__': obj1=ComparisonOverload(13) obj2=ComparisonOverload(7) print("obj1>obj2:",obj1>obj2) print("obj1<obj2:",obj1<obj2) print("obj1==obj2:",obj1==obj2) print("obj2!=obj1:",obj1!=obj2) print("obj2<=obj1:",obj1<=obj2) print("obj2>=obj1:",obj1>=obj2)
Output:
obj1>obj2: True
Overloading < operator
obj1<obj2: False
Overloading == operator
obj1==obj2: False
Overloading != operator
obj2!=obj1: True
Overloading <= operator
obj2<=obj1: False
Overloading >= operator
obj2>=obj1: True
Interview Questions on Comparison Operators in Python
Q1. Are the strings “abc” and “a b c” equal. Show it using coding and check the relation between the.
Ans 1. No, the strings “abc” and “a b c” are not the same as the spaces are also considered in Python.
Example of using == operator to compare two strings:
'abc'=='a b c'
Output:
The 2nd characters are b and space. Since the ASCII value of b is greater than space, “abc” is greater than “a b c”.
Example of using > operator to compare two strings:
'abc'>'a b c'
Output:
Q2. Are the sets {1,2,3,4} and {4.0,2.0,3.0,1.0} equal? Show it by coding.
Ans 2. Yes, the sets {1,2,3,4} and {4.0,2.0,3.0,1.0} are equal. This is shown in the below coding snippet.
Example of using == operator to compare two sets:
{1,2,3,4} == {4.0,2.0,3.0,1.0}
Output:
This is because the set arranges its values in ascending order. Though the data types are not the same, the values are the same. So, the result is True.
Q3. By coding show which of the comparison operators give true with on comparing the numbers 9 and 9.0?
Ans 3. Example of using == operator to compare two numbers:
9==9.0
Output:
Example of using >= operator to compare two numbers:
9>=9.0
Output:
Example of using <= operator to compare two numbers:
9<=9.0
Output:
Therefore, ==,<= and >= give True on comparing 9 and 9.0.
Q4. Return a tuple of Trues and False obtained by comparing the numbers 5 and 9 by the six comparison operators.
Ans 4. We can do the comparison and separate each by comma to result in a tuple.
Example of getting a tuple on comparing two numbers with different operators:
5>9,5<9,5>=9,5<=9,5==9,5!=9
Output:
You can check its type by using the type() function.
Example of using type() to check the data type:
a=5>9,5<9,5>=9,5<=9,5==9,5!=9 type(a)
Output:
Q5. Compare the following names of two students and tell whose roll number will be before that of the other. Then names are “a. Python”, “a. PYTHON”.
Ans 5. Example of using > operator to compare two strings :
"a. Python" > "a. PYTHON"
Output:
Since a.PYTHON is less than a.Python, a.PYTHON comes first roll number wise.
Quiz on Comparison Operators in Python
Conclusion
In this article, we learned about different comparison operators. Along with this we also saw some examples. Finally, we practiced some interview questions.
Hoping that this article helped you learn something new. Happy Coding.