Python Comparison Operators

blog-15.jpg

Python Comparison Operators are the basic and essential blocks of conditional statements. They are used to compare two values and return the boolean result, True or False. Other than conditional statements, these are also widely used in decision-making, control flow, validation, sorting, filtering, and more. In this article, you will understand Python comparison operators, their syntax, and how they are applied in the real world in detail.

Table of Contents:

What are Comparison Operators in Python?

Comparison operators are one of the several types of Python operators. They help you compare two values and evaluate their relationship. These operators are mostly used in conditional statements like if, elif, and while to control the flow of the program based on specific criteria. The result of these expressions is always a boolean value, either True or False. There are six fundamental types of comparison operators in Python.

Types of Comparison Operators in Python

The comparison operators in Python are equal to, not equal to, greater than, less than, greater than or equal to, and less than or equal to. Here is the list of Python comparison operators and their usage. 

1. Equal to (==) Operator in Python

This operator checks whether the two values, or operands, are equal or not. If they are equal, it will return True, and if they are not, it will return False. 

Example for Equal to (==) Operator in Python:

Python

Output:

Equal to (==) Operator

Explanation: Here, the values were compared, and based on the result, the if block or else block was printed.

2. Not Equal To (!=) Operator in Python

This operator returns True for unequal values or operands. If they are equal, the operator will return False.

Example for Not Equal To (!=) Operator in Python:

Python

Output:

Not Equal To Operator in Python

Explanation: Here, since x is not equal to 5, the if block condition was validated, and hence, the code in the if block got printed. Whereas y was equal to 5, hence nothing was printed on the output console.

3. Greater Than (>) Operator in Python

This operator will return True if the first operand is greater than the second operand. If it is not, it will simply return False.

Example for Greater Than (>) Operator in Python:

Python

Output:

Greater Than operator

Explanation: Here, since b is greater than a, it validates the condition in the elif block, and hence, the elif block was implemented. 

4. Less Than (<) Operator in Python

This operator compares the two values and checks whether the left value is smaller than the right value. If that is the case, it will return True or otherwise, it will return False. 

Example for Less Than (<) Operator in Python:

Python

Output:

less than operator

Explanation: Here, since a was less than b, the ‘if’ block code was executed. 

5. Greater Than or Equal to (>=) Operator in Python

This operator is a mix of the equal to operator and the greater than operator. This operator, when used in an expression, will return True if the first operand is greater than or equal to the second operand. 

Example for Greater Than or Equal to (>=) Operator in Python:

Python

Output:

greater than equal to operator

Explanation: Here, a was greater than or equal to b. Therefore, it was printed on the output console based on the condition check.

6. Less Than or Equal to (<=) Operator in Python

This operator is made from the ‘less than’ symbol and the ‘equal to’ symbol. This operator returns True for the expression that has the left operand less than or equal to the right operand. Else it returns False.

Example for Less Than or Equal to (<=) Operator in Python:

Python

Output:

less than equal to operator

Explanation: Here, a is less than b. This made the condition in the if block true. Therefore, the if block was executed.

Python Comparison Operator Chaining

In Python, you can chain various comparison operators like we do in mathematics without using parentheses. This means you can write (a > 10) and (a < 20 ) as 10 < a < 20, and both will give the same result. The advantage of this comparison is that Python evaluates each condition from left to right and will stop as soon as any part of the chain fails.

How it Works: The interpreter automatically applies a logical operator between the comparison operators when you chain them. This means that a < b < c is interpreted as (a < b) and (b < c).

Example for chaining comparison operator:

Python

Output:

chaining comparison operators

Explanation: Here, the grade of the student was 82. According to the condition, the result was printed. 

Summary Table

Operator Name Description Example Result
== Equal to Checks if two values are equal 5 == 5 True
!= Not equal to Checks if two values are not equal 5 != 3 True
> Greater than True if the left operand is greater 7 > 3 True
< Less than True if the left operand is smaller 4 < 9 True
>= Greater than or equal to True if left is greater or equal 10 >= 10 True
<= Less than or equal to True if the left is smaller or equal 6 <= 6 True

Python Comparison Operators vs Logical Operators

Aspect Python Comparison Operators Python Logical Operators
Purpose Used to compare two values and return a Boolean (True or False). Used to combine or modify Boolean values.
Common Operators ==, !=, <, >, <=, >= (relational operators in Python) and, or, not (logical operators in Python)
Example Usage age == 18 or score >= 50 checks equality or range using comparison operators in Python. (age > 18 and has_id) uses multiple conditions with Python logical operators.
Return Type Always returns a Boolean after comparing values. Returns a Boolean by evaluating logical relationships.
Data Types Used Compares numbers, strings, Booleans, etc. Operates on Boolean values only.
Use in Conditions Fundamental in creating conditional checks using the == operator in Python or other comparisons. Essential for combining conditions in if, elif, and while statements with conditional operators in Python.

How Python Comparison Operators Work with Different Data Types?

Python allows you to compare other data types like strings, tuples, and lists as well, in addition to integers. This means you can compare a string with a string, a tuple with a tuple, and a list with a list. Comparing two incompatible data types is not supported. You cannot compare a string with a tuple, and so on. 

Strings in Python 

When you are using comparison operators with strings, Python compares each character of the string based on their ASCII Code. This is called the Lexicographical Comparison. Remember, uppercase letters come before the lowercase letters in the ASCII code. 

Example for Lexicographical Comparison:

Python

Output:

Comparison Operators with Different Data Types

Explanation: Here, the first characters M and D are compared. The ASCII value of M is 77, and D is 68. Since 77 > 68, “Mumbai” comes after “Delhi” alphabetically.

Tuples and Lists in Python

With sequential data types like tuples and lists, the interpreter compares each element one by one, from left to right. It moves until it finds one false comparison and returns False then and there.

Example for tuples and lists:

Python

Output:

Comparison Operators with Different Data Types

Explanation: Here, in tuples, a is less than b because the third element in a is less than in b. In the last example, list 1 has only two elements, whereas list 2 has 3. Therefore, list1 is considered less than list2. The shorter lists are considered smaller if all earlier elements are equal.

Boolean in Python

The boolean values in Python act like integers. True value takes the integer value of 1, and the False value takes the integer value of 0. Hence, if we compare the boolean values with the less than or greater than operator, the answer will be accordingly.

Example for Boolean in Python:

Python

Output:

Comparison Operators with Different Data Types

Explanation: Here, True is considered 1, and False is considered 0. The comparison results reflect their integer values (1 for True, 0 for False).

How Comparison Operators Work with Booleans?

  1. Python comparison operators return Boolean values (True or False) based on logical evaluation.
  2. Booleans in Python are internally treated as integers: True = 1, False = 0. This allows Booleans to be compared directly using standard Python operators. The == operator in Python checks if two values are equal (returns True if the same).
    The != operator checks if two values are different (returns True if not equal).
  3. The difference between == and != in Python is that one checks for equality, and the other for inequality. Python relational operators, like <, >, <=, and >= also work with Booleans using their numeric values.
  4. Example: True > False is True because 1 > 0.
    These behaviors are useful in conditional operators in Python, such as if, elif, and while statements. Python allows simplified Boolean checks: if user_active: is the same as if user_active == True:.
  5. Understanding this helps in writing clean, efficient, and readable logic using comparison operators in Python.

Difference Between == and is in Python

Aspect == Operator in Python is Operator in Python
Purpose Checks if the values of two variables are equal. Checks if two variables refer to the same object in memory.
Type of Comparison Value equality Object identity
Usage Example a == b returns True if both have the same content. a is b returns True only if both point to the same memory location.
Works With All data types like numbers, strings, lists, etc. Best used with singletons like None, or to check object identity.
Common Use Case Comparing values in logic and conditions. E.g., if a == 5: Checking for None or verifying object identity. E.g., if obj is None:
Result Type Returns a Boolean (True or False) based on value match. Returns a Boolean based on identity match (memory address).

Common Mistakes Using Comparison Operators in Python

  1. Beginners often confuse = (assignment) with == (equality) in Python, comparison operators can lead to syntax or logic errors.
  2. Writing if is_active == True: is redundant; the cleaner Pythonic way is simply if is_active:.
  3. Misusing the != operator, especially in complex conditions, can cause logical errors in program flow.
  4. Using relational operators in Python, like <, >, <=, >= with incompatible types (e.g., string vs integer) causes TypeError.
  5. Many confuse identity Python operators (is, is not) with equality operators (==, !=); the former compares memory location, the latter compares value.
  6. Incorrect chaining of comparisons, like a > b < c, may produce unexpected results unless the expression logic is fully understood.
  7. Proper use of Python comparison operators requires understanding their behavior, syntax, and how they interact with data types and logic flow.

Real-World Example of Comparison Operators in Python

Comparison operators are used nearly everywhere where there are conditional statements. The conditions are checked using these comparison operators. Algorithms use these comparison operators to validate some conditions based on which they move forward. Here we are using the Bubble sort algorithm implementation to showcase the working of comparison operators. We are going to sort the students’ grades in ascending order to determine the rankings.

Bubble sort compares two adjacent values using the greater than (>) comparison operator to check whether the given list is in order or out of order.

Example:

Python

Output:

Comparison Operators with Different Data Types

Explanation: Here, we compared the adjacent values and sorted the list in ascending order according to the student’s grades.

Conclusion

Comparison operators are essential in programming, especially for tasks like sorting and searching, two of the most common operations. They help define conditions that guide control flow based on how comparisons are evaluated. Mastering comparison operators is key to writing clean, logical Python code that dynamically reacts to data. Understanding and practicing them lays the foundation for building smart, responsive applications that assess and act based on varying data conditions.

To take your skills to the next level, check out this Python training course and gain hands-on experience. Also, prepare for job interviews with Python interview questions prepared by industry experts.

 

Master essential Python Basics like file handling and working with modules through these articles

How to Parse a String to a Float or Int in Python – Learn how to parse a string to a float or int in Python with this simple and effective guide.
Python Arithmetic Operators – Discover how to use Python arithmetic operators efficiently with this beginner-friendly guide.
Python Assignment Operator – Explore the basics of Python’s assignment operator in this clear and concise guide.
Python Bitwise Operators – Get to know how Python bitwise operators work through this simple explanation.
Python Membership and Identity Operators – Understand how membership and identity operators function in Python with this easy guide.
Python Docstrings – Grasp the concept of Python docstrings quickly with this no-fuss introduction.
Access Environment Variable Values in Python – Find out how to read environment variable values in Python with this practical guide.
Python: How to Get the Last Element of List – Check out how to retrieve the last element of a list in Python using this easy-to-follow tip.
Access Index Using For Loop in Python – See how to access the index in a Python for loop effectively with this beginner’s walkthrough.

Python Comparison Operators – FAQs

Q1. Are string comparisons case-sensitive?

Yes, since uppercase letters have lower ASCII values compared to lowercase ones.

Q2. What if I compare two incompatible types, such as int and str?

It will raise a TypeError in Python.

Q3. Can I chain comparison operators like a < b < c?

Yes, Python allows chaining and interprets it as (a < b) and (b < c).

Q4. How are tuples and lists compared in Python?

Python compares tuples and lists element-wise from left to right and returns True or False based on the first unmatched pair or complete equality.

Q5. What do comparison operators return in Python?

They return a boolean value, i.e., True or False.

Q6. What are the six comparison operators in Python?

Python supports six comparison operators: ==, !=, >, <, >=, and <=.

Q7. How do Boolean comparisons work in Python?

They evaluate expressions and return either True or False based on logical conditions.

Q8. What happens if I compare an int and a string in Python?

It raises a TypeError since Python doesn’t allow direct comparison between int and str.

Q9. Can I use comparison operators inside an if statement in Python?

Yes, comparison operators are commonly used within if statements to guide program flow.

Q10. How to use comparison operators in Python?

Comparison operators in Python compare values and return True or False, like a < b or x == y. They're often used in if statements to control code execution.

About the Author

Senior Consultant Analytics & Data Science, Eli Lilly and Company

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration. 

EPGC Data Science Artificial Intelligence