Python’s comparison operators are fundamental tools for evaluating relationships between values. Understanding how these operators work is important for writing effective and efficient Python code. This guide provides a clear explanation of each operator with illustrative examples.
The Six Main Comparison Operators
Python offers six primary comparison operators, each designed to test a specific relationship:
Operator | Meaning | Example | Result |
---|---|---|---|
== |
Equal to | 5 == 5 |
True |
!= |
Not equal to | 5 != 10 |
True |
> |
Greater than | 10 > 5 |
True |
< |
Less than | 5 < 10 |
True |
>= |
Greater than or equal to | 10 >= 10 |
True |
<= |
Less than or equal to | 5 <= 10 |
True |
Let’s look at each with code examples:
1. ==
(Equal to)
This operator checks if two values are equal. Note that it performs a value comparison, not an identity comparison (we’ll discuss that later).
= 5
x = 5
y print(x == y) # Output: True
= [1, 2, 3]
a = [1, 2, 3]
b print(a == b) # Output: True (value comparison)
= a
c print(a == c) # Output: True (same object in memory)
2. !=
(Not equal to)
This operator returns True
if two values are not equal.
= 5
x = 10
y print(x != y) # Output: True
= [1, 2, 3]
a = [3, 2, 1]
b print(a != b) # Output: True
3. >
(Greater than) and <
(Less than)
These operators compare the magnitude of numerical values.
= 10
x = 5
y print(x > y) # Output: True
print(y < x) # Output: True
= "apple"
a = "banana"
b print(a < b) # Output: True
4. >=
(Greater than or equal to) and <=
(Less than or equal to)
These operators check if a value is greater than or equal to, or less than or equal to, another value.
= 10
x = 10
y print(x >= y) # Output: True
print(x <= y) # Output: True
= 15
x = 10
y print(x >= y) # Output: True
print(y <= x) # Output: True
Chaining Comparison Operators
Python allows for elegant chaining of comparison operators:
= 5
x print(1 < x < 10) # Output: True (equivalent to 1 < x and x < 10)
print(10 > x > 1) #Output: True (equivalent to 10 > x and x > 1)
Boolean Comparisons
Comparison operators also work with boolean values:
= True
a = False
b print(a == b) # Output: False
print(a != b) # Output: True
print(a > b) # Output: True (True is considered "greater" than False)