Python Comparison Operators with Syntax and Examples

Free Python courses with 57 real-time projects - Learn Python

In our previous article, we talked about Python bitwise operators. Today, we focus our words on Python Comparison Operators.

These are also called relational operators in Python.

Along with this, we will learn different types of Comparison Operators in Python: less than, greater than, less than or equal to, greater than or equal to, equal to, and not equal to with their syntax and examples.

So, let’s start the Python Comparison Operators Tutorial.

Python Comparison Operators with Syntax and Examples

Python Comparison Operators with Syntax and Examples

What is Python Comparison Operator?

A comparison operator in python, also called python relational operator, compares the values of two operands and returns True or False based on whether the condition is met.

We have six of these, including and limited to- less than, greater than, less than or equal to, greater than or equal to, equal to, and not equal to.

So, let’s begin with the Python Comparison operators.

1. Python Less Than (<) Operator

The first comparison operator in python we’ll see here is the less than operator. Denoted by <, it checks if the left value is lesser than that on the right.

>>> 3<6

Output

True

Since 3 is lesser than 6, it returns True.

>>> 3<3

Output

False

Because 3 is equal to 3, and not less than it, this returns False.

But let’s see if we can apply it to values other than ints.

>>> 3<3.0

Output

False

Here, 3 is an int, and 3.0 is a float, but 3 isn’t lesser than 3.0, or vice versa.

>>> 3.0<3

Output

False
>>> 'Ayushi'<'ayushi'

Output

True

This one results in True because when comparing strings, their ASCII values are compared. The ASCII value for ‘A’ is 65, but that for ‘a’ is 97.

Hence, ‘A’ is lesser than ‘a’. Likewise, ‘Ayushi’ is lesser than ‘ayushi’.

>>> 0.9999999<True

Output

True

Yes, it does. But what’s fascinating is that it works on containers like tuples as well. Let’s see some of these.

>>> (1,2,3)<(1,2,3,4)

Output

True
>>> (1,3,2)<(1,2,3)

Output

False
>>> (1,2,3)<(1,3,2)

Output

True
>>> ()<(0,)

Output

True

But you can’t compare tuples with different kinds of values.

>>> (1,2)<('One','Two')

Output

Traceback (most recent call last):File “<pyshell#84>”, line 1, in <module>(1,2)<(‘One’,’Two’)

TypeError: ‘<‘ not supported between instances of ‘int’ and ‘str’

However, if you get comparable elements at the same indices, it is possible to compare two tuples.

>>> (1,'one')<(2,'two')

Output

True

And when we say same indices, we mean it.

>>> (1,'one')<('two',2)

Output

Traceback (most recent call last):File “<pyshell#86>”, line 1, in <module>(1,’one’)<(‘two’,2)

TypeError: ‘<‘ not supported between instances of ‘int’ and ‘str’

>>> [0]<[False]

Output

False
>>> {1,2,3}<{1,3,2}

Output

False

Here, because the other set rearranges itself to {1,2,3}, the two sets are equal. Consequently, it returns False.

>>> {1:'one',2:'two'}<{1:'three',2:'four'}

Output

Traceback (most recent call last):File “<pyshell#91>”, line 1, in <module>

{1:’one’,2:’two’}<{1:’three’,2:’four’}

TypeError: ‘<‘ not supported between instances of ‘dict’ and ‘dict’

If you face any doubt in Python Comparison Operators? Please Comment.

2. Python Greater Than (>) Operator

Let’s see the Greater than Python Comparison Operator

Now that we’ve seen which constructs we can apply these operators to, we will focus on the operators now on.

The greater than an operator, denoted by >, checks whether the left value is greater than the one on the right.

>>> 0.5>False

Output

True
>>> 3,4,5>3,4,5.0

Output

(3, 4, True, 4, 5.0)

Hey, this created a tuple, when all we wanted to do was compare. This is because it took 5>3 as a value (True). It put this as a value in the tuple.

So let’s try to find our way around this.

>>> 3,4,5 > 3,4,5.0

Output

(3, 4, True, 4, 5.0)

So we see that spaces didn’t do it. Let’s try something else.

>>> 3,4,5>(3,4,5.0)

Output

Traceback (most recent call last):File “<pyshell#96>”, line 1, in <module>

3,4,5>(3,4,5.0)

TypeError: ‘>’ not supported between instances of ‘int’ and ‘tuple’

Hmm, we think we need to put parentheses around both tuples.

>>> (3,4,5)>(3,4,5.0)

Output

False

Yes, it works now. We told you earlier that it’s okay to skip parentheses while declaring a tuple.

But in this situation, it took 3, 4, and 5 to be ints, and believed that we were declaring a tuple, and not comparing two.

You should take care of such situations by coding carefully.

3. Less Than or Equal To (<=) Operator

We guess the next two operators won’t be much of a problem with you. We will quickly learn how to write less than or equal to in Python.

The less than or equal to operator, denoted by <=, returns True only if the value on the left is either less than or equal to that on the right of the operator.

>>> a=2
>>> a<=a*2

Output

True

4. Equal To or Greater Than – Python (>=) Operator

Likewise, this operator returns True only if the value on the left is greater than or equal to that on the right.

>>> from math import pi
>>> 3.14>=pi

Output

False

Any doubt in Python Comparison Operators? Please Ask us in the comment.

5. Python Equal To (==) Operator

The final two operators we’ll be looking at are equal to (==) and not equal to (!=).

The equal to operator returns True if the values on either side of the operator are equal.

>>> 3=='3'

Output

False

As we know, 3 is an integer, and ‘3’ is a string. Hence, they’re unequal. Let’s take about a couple more examples.

>>> {1,3,2}=={1,2,3}

Output

True

Like you know, a set rearranges itself. This is why this returns True.

>>> 0==False

Output

True

Of course, False has an integer value of 0. Therefore, it returns True.

6. Python Not Equal Operator (!=) Operator

Finally, we’ll discuss the not equal to operator. Denoted by !=, this does the exact opposite of the equal to operator.

It returns True if the values on either side of the operator are unequal.

>>> 3!=3.0

Output

False
>>> 3==3.0

Output

True

Note that the operator <> for the same purpose is no longer functional.

This is all about the Python Comparison Operators.

Python Interview Questions on Comparison Operators

  1. How many comparison operators are there in Python?
  2. How do you use greater than in Python?
  3. What are the different types of operators in Python?
  4. How does the operator work in Python?
  5. What are relational operators in Python?

Conclusion

Concluding for today, we learned six comparison operator in python.

These are- python less than, python greater than, Less Than or Equal To, Equal to or greater than, Python Equal To and Python Not Equal Operator.

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

24 Responses

  1. JYOTI SHARMA says:

    >>> (1,2,3)<(1,3,2)

    How does the above expression evaluate to True?
    I believe this is comparing the value in tuples as per their position( like 1<1, 2<3,3<2)

    • DataFlair Team says:

      Hi Jyoti,
      Thanks for the query for Python comparison operator, in tuple comparison for Python, (1,2,3)<(1,3,2) evaluates to True. Let's see how.

      It compares 1 and 1; these are equal. So now, it compares 2 and 3 (second elements in the tuples); since 2 is less than 3, it stops here and returns True. If both values were 2 instead, it would move on to compare the third elements (3 and 2).
      Hope, it will help you!
      Regards,
      DataFlair

      • JAPHETH miles says:

        well explained 10/10 my rating

        • Kristy says:

          Dataflari team –
          Here you mention nothing of rearranging; instead you mention a digit to digit compare.
          This answer seems to contradict what was discussed in the above Python Operators lesson.
          (mentions that a tuple would rearrange itself)

          >>> {1,3,2}=={1,2,3}
          Output

          True
          Like you know, a set rearranges itself. This is why this returns True.

          >>> {1,2,3}<{1,3,2}
          Output

          False
          Here, because the other set rearranges itself to {1,2,3}, the two sets are equal. Consequently, it returns False.

  2. sagar says:

    why we get this error

    TypeError: ‘>’ not supported between instances of ‘int’ and ‘tuple’

    please explain this

    • DataFlair Team says:

      Hi, Sagar
      If you try to compare an integer value with a tuple of any kind, which is a collection of values, you’ll get the error you mentioned above.
      For example, try this in the interpreter:
      1(3,4,5.0)
      Here, we do not have two tuples to compare. Rather, it creates a tuple with three values- 3, 4, and 5>(3,4,5.0)- which would be a Boolean if it were permitted.
      Hope, it helps!

  3. Rahul Ranjan says:

    How does
    >>> from math import pi
    >>> 3.14>=pi

    return false.
    pi is equal to 3.14. It should return true because the operator says greater than or equal to

    • DataFlair Team says:

      Hello Rahul,
      Of course. The value of pi is not just 3.14, but somewhere around 3.141592653589793 for the variable pi from the math module (although technically, you cannot accurately write it down as a decimal; so far, it has been calculated to 31.4 trillion decimal places). And 3.14 is indeed lesser than the value 3.141592653589793, which is why it returns False.

  4. Pooja says:

    Hi

    Can someone help me with this query

    ID = input (“Please enter User ID: “)
    valid = False

    while valid == False:
    if len(ID) != 6:
    ID = input(“Invalid userID – please re-enter: “)
    else:
    valid = True
    partID = ID[2:6]
    print (“partID”,partID)

    if partID “6999”:
    valid = False
    ID = input(“Invalid userID – please re-enter: “)
    else:
    firstPart = ID[0:2]
    if firstPart != “AA” and firstPart != “BX”: // In this statement ideally it should work with OR whereas it is working with AND Can anyone explain Why??
    valid = False
    ID = input(“Invalid userID – please re-enter: “)

    else:
    print(“correct id”)

    input(“\nPress any key to exit “)

    • priya says:

      hi pooja,
      In your code if partID “6999” : it should be like if partID ==’6999

      if firstPart != “AA” and firstPart != “BX”: // In this statement ideally it should work with OR whereas it is working with AND Can anyone explain Why??

      This statement can be written using or statement as,
      if (!(firstPart ==’AA’ or firstPart ==’BX’))

    • DataFlair says:

      If you want you firstPart to neither start with “”AA”” nor with “”BX”” then the given code is fine but if you use or here it will valid in both the cases. Consider firstPart is “”AA”” then
      if firstPart != “AA” or firstPart != “BX” will evaluate to
      if false or true which is
      if true

      Hence, And should be used here.

  5. sri says:

    HOW to define a variable that in range like below
    invalidinput = 2 how this can be arrived

    ex if a variable can be less than zero and grater than 2 how to arrive at this

    • DataFlair says:

      You can use the following code snippet:

      var = input (“Please enter: “)
      valid = False

      while valid == False:
      if var2:
      var = input(“Invalid – please re-enter: “)

  6. shakib says:

    hello sir it is showing > is not supported between str and int ..how can i resove it plzz help

    • DataFlair says:

      Yeah, you cannot compare a string and an integer. You have to use two homogenous data types with this.
      Eg:
      if 20>6:
      print(“”OKAY””)
      else:
      print(“”NOT OKAY””)

  7. Yashwardhan says:

    Input: [1,2,8,9] < [9,1]
    Output: true
    How???

    • DataFlair says:

      It compares elements of the two lists. Since the first element of the right list is greater then the first element of left list it evaluates to true

  8. Akarsha tecmo says:

    hi Shakib
    you have to just convert your string to an integer.
    ex:
    a=’10’ # a is a string
    a>2 # this returns an error as you got
    #so you have to do just
    int(a)>2

  9. FUJI ANSORIYADI says:

    i just got a question about {7,4,5)>={7,4,5,2}. it is a set and will rearrange itself like {4,5,7}>={2,4,5,7} but the question is why its return False? please explain it… thanks

  10. Muhammad Faizan says:

    Very well Expalined…. Thanks Alot!

    • DataFlair Team says:

      We sincerely thank you for your kind words. Your feedback is priceless to us ,don’t forget to visit our python projects.

  11. Godavarthi Madhuri says:

    {‘a’,’b’,’c’}>{1,2,3}

    Output:False

    Can anyone explain how the output is false?

Leave a Reply

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