Python Comparison Operators

Python comparison operators are the backbone of every decision your code makes. Whenever you write an if statement, a while loop, or a filter condition, you are almost certainly using a comparison operator under the hood. These operators take two values, compare them, and return either True or False — a Python boolean. Understanding how each comparison operator works, and where it applies, gives you precise control over your program's logic. This guide walks through all six Python comparison operators one by one, then covers type comparisons, the important difference between equality and identity, and how to chain comparisons together cleanly.

What Are Python Comparison Operators

Python comparison operators (also called relational operators) compare two operands and produce a boolean result. Python provides six of them:

OperatorMeaning
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to

Every comparison operator returns True or False. That result can be stored in a variable, used directly in a conditional, or combined with logical operators like and, or, and not.

You can read the full reference for these in the Python documentation on comparisons.

== The Equality Operator in Python

The double equals sign checks whether two values are equal. It is one of the most frequently used Python comparison operators. A common beginner mistake is confusing a single equals sign (assignment) with double equals (comparison) — they do completely different things.

When you write "x = 10", you are assigning the value 10 to x. When you write "x == 10", you are asking whether x currently holds the value 10 and getting back True or False.

score = 85

print(score == 85)
print(score == 90)
print("hello" == "hello")
print("hello" == "Hello")
True
False
True
False

The last comparison returns False because Python strings are case-sensitive. The equality operator compares the actual content character by character, so a capital H and a lowercase h are treated as different values.

The equality operator works across many types — integers, floats, strings, lists, and more. When comparing lists or other collections, Python checks whether the contents are equal, not whether they point to the same place in memory.

list_a = [1, 2, 3]
list_b = [1, 2, 3]
list_c = [1, 2, 99]

print(list_a == list_b)
print(list_a == list_c)
True
False

!= The Not Equal Operator

The not equal operator returns True when two values are different from each other, and False when they are the same. It is the direct opposite of ==. This operator is useful when you want to run code only if something has changed, or when you want to skip a particular value.

current_status = "inactive"

print(current_status != "active")
print(current_status != "inactive")

temperature = 100
print(temperature != 100)
print(temperature != 50)
True
False
False
True

In the first pair, comparing "inactive" to "active" gives True because they differ. Comparing "inactive" to "inactive" gives False because they are the same. The not equal operator is extremely common in loop conditions where you want to keep running until a value changes.

> Greater Than and < Less Than

These two Python comparison operators check the relative size or order of two values. Greater than (>) returns True when the left operand is larger. Less than (<) returns True when the left operand is smaller.

They work naturally with numbers and also with strings, where Python compares characters based on their Unicode code points from left to right.

apples = 15
oranges = 10

print(apples > oranges)
print(apples < oranges)
print(oranges < apples)
True
False
True

With strings, comparisons are done alphabetically using Unicode values. Lowercase letters have higher Unicode values than uppercase letters in Python.

print("banana" > "apple")
print("Zebra" < "apple")
print("cat" < "dog")
True
True
True

"Zebra" is less than "apple" because uppercase Z has a lower Unicode value than lowercase a. This is something to watch for when sorting or comparing strings that mix cases.

>= Greater Than or Equal To and <= Less Than or Equal To

These operators extend the greater than and less than comparisons to also return True when the two values are exactly equal. They are especially useful for range checks — for example, confirming that a value falls within minimum and maximum bounds.

age = 18
minimum_age = 18

print(age >= minimum_age)
print(age > minimum_age)

speed = 55
speed_limit = 60

print(speed <= speed_limit)
print(speed < speed_limit)
True
False
True
True

Notice that "age >= minimum_age" returns True because 18 equals 18, but "age > minimum_age" returns False because 18 is not strictly greater than 18. This distinction matters in boundary conditions. Choosing the wrong operator at a boundary is a very common source of off-by-one errors.

Comparing Different Data Types

Python comparison operators behave predictably when comparing values of the same type, but comparing different types can produce errors or unexpected results depending on what you are comparing.

In Python 3, comparing incompatible types like an integer and a string with greater than or less than raises a TypeError. However, the equality operator == does not raise an error — it simply returns False when the types are incompatible.

number = 42
text = "42"

print(number == text)
print(number == int(text))
False
True

The first comparison returns False because an integer and a string are never equal in Python, even if the string contains the same digits. Converting the string to an integer first makes the comparison meaningful.

print(3.0 == 3)
print(3.14 > 3)
True
True

Integers and floats can be compared directly in Python because Python promotes the integer to a float before comparing. So 3.0 and 3 are considered equal.

Python == vs is: Equality vs Identity

This is one of the most important distinctions in Python. The == operator checks whether two values are equal in content. The "is" keyword checks whether two variables point to the exact same object in memory — not just equal values, but literally the same object.

x = [10, 20, 30]
y = [10, 20, 30]
z = x

print(x == y)
print(x is y)
print(x is z)
True
False
True

Even though x and y contain identical elements, they are two separate list objects stored at different memory addresses, so "x is y" is False. But z was assigned to point at the same object as x, so "x is z" is True.

For small integers and short strings, Python often caches and reuses objects — a behavior called interning — which can make "is" return True even for separately created values. But you should never rely on this behavior for equality checks. Always use == when you want to compare values, and reserve "is" for checking against None or other singletons.

result = None

if result is None:
    print("No result yet")

value = 0
if value == 0:
    print("Value is zero")
No result yet
Value is zero

Chaining Python Comparison Operators

One of Python's elegant features is that you can chain comparison operators in a single expression. In most programming languages you would need to write "x > 0 and x < 100", but Python allows "0 < x < 100" directly.

score = 75

if 0 <= score <= 100:
    print("Valid score")

temperature = 22

if 18 < temperature < 30:
    print("Comfortable temperature")
else:
    print("Too hot or too cold")
Valid score
Comfortable temperature

Python evaluates chained comparisons from left to right, and each value in the chain is only evaluated once. This makes chained comparisons both readable and efficient. They are evaluated as "0 <= score AND score <= 100" internally, but the syntax is much cleaner.

You can chain more than two comparisons too, though using more than three in a chain can start to reduce readability.

a, b, c, d = 1, 5, 10, 20

print(a < b < c < d)
print(a < b > c < d)
True
False

Comparison Operators in Conditional Statements

Python comparison operators are most commonly used inside if, elif, and while statements. The result of a comparison — a boolean — controls which block of code runs.

rainfall = 45

if rainfall > 100:
    print("Heavy rain warning")
elif rainfall > 50:
    print("Moderate rainfall")
elif rainfall >= 20:
    print("Light rainfall")
else:
    print("Minimal or no rain")
Light rainfall

Since 45 is not greater than 100 or 50, but is greater than or equal to 20, the third branch runs.

Comparison operators also appear in while loops to control iteration. The loop continues as long as the comparison returns True.

count = 0
while count < 5:
    print(f"Count is {count}")
    count += 1
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4

And they work naturally inside list comprehensions and filter conditions to select only values that meet a criterion.

temperatures = [14, 22, 31, 18, 27, 9, 25]
warm_days = [t for t in temperatures if t >= 20]
print(warm_days)
[22, 31, 27, 25]

Storing Comparison Results in Variables

Because Python comparison operators return True or False, their results are regular boolean values that can be stored in variables, passed to functions, or combined with logical operators.

x = 50
is_positive = x > 0
is_large = x >= 100

print(is_positive)
print(is_large)
print(is_positive and not is_large)
True
False
True

This pattern is useful when you need to compute a condition once and check it in multiple places, or when you want to give a meaningful name to a complex condition.

You can also combine comparison results using "and", "or", and "not" from Python's boolean operators to build compound conditions.

height = 175
weight = 70

is_tall = height > 170
is_average_weight = 60 <= weight <= 90

if is_tall and is_average_weight:
    print("Tall and healthy weight range")
Tall and healthy weight range

Full Working Example

This example brings together all six Python comparison operators, chaining, equality vs identity, and using comparisons in conditions and list comprehensions — all in one self-contained script.

def classify_grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

student_scores = {
    "Alice": 93,
    "Bob": 74,
    "Charlie": 58,
    "Diana": 81,
    "Edward": 67,
    "Fiona": 100,
}

print("=== Grade Report ===")
for name, score in student_scores.items():
    grade = classify_grade(score)
    print(f"{name}: {score} -> Grade {grade}")

passing_students = [name for name, score in student_scores.items() if score >= 60]
failing_students = [name for name, score in student_scores.items() if score < 60]

print("\n=== Passing Students ===")
print(passing_students)

print("\n=== Failing Students ===")
print(failing_students)

scores = list(student_scores.values())
highest = max(scores)
lowest = min(scores)

print(f"\nHighest score: {highest}")
print(f"Lowest score: {lowest}")
print(f"All scored above 50: {all(s > 50 for s in scores)}")
print(f"Anyone scored perfectly: {any(s == 100 for s in scores)}")

top_and_bottom_differ = highest != lowest
print(f"\nTop and bottom scores are different: {top_and_bottom_differ}")

ref_list = [90, 80, 70]
copy_list = [90, 80, 70]
same_list = ref_list

print(f"\nref_list == copy_list: {ref_list == copy_list}")
print(f"ref_list is copy_list: {ref_list is copy_list}")
print(f"ref_list is same_list: {ref_list is same_list}")

average = sum(scores) / len(scores)
print(f"\nClass average: {average:.1f}")
if 70 <= average < 80:
    print("Class average is in the C range")
elif average >= 80:
    print("Class average is B or above")
else:
    print("Class average is below C")
=== Grade Report ===
Alice: 93 -> Grade A
Bob: 74 -> Grade C
Charlie: 58 -> Grade F
Diana: 81 -> Grade B
Edward: 67 -> Grade D
Fiona: 100 -> Grade A

=== Passing Students ===
['Alice', 'Bob', 'Diana', 'Edward', 'Fiona']

=== Failing Students ===
['Charlie']

Highest score: 100
Lowest score: 58
All scored above 50: True
Anyone scored perfectly: True

Top and bottom scores are different: True

ref_list == copy_list: True
ref_list is copy_list: False
ref_list is same_list: True

Class average: 78.8
Class average is in the C range