Python Comparison Operators
Comparison operators are the engine behind every decision your program makes. They evaluate two
values and return a boolean True or
False — powering every
if statement,
while loop, and filter. This chapter covers all six
comparison operators in depth, Python's unique chained comparison syntax, how comparisons work
across different data types, and the critical float comparison pitfall every developer must
know.
What Are Comparison Operators?
Comparison operators (also called relational operators) compare two values and
always return a boolean — either True or
False. They are the fundamental building blocks of
conditional logic, used in every if statement,
while loop condition, list comprehension filter, and sorting
key.
Python has exactly six comparison operators. They work on numbers, strings,
lists, tuples, and any objects that define the comparison magic methods (__eq__, __lt__, etc.).
bool — a subclass of
int. This means
True == 1 and
False == 0. You can therefore use comparison results
directly in arithmetic: sum(x > 0 for x in nums) counts
positive numbers.
All Six Comparison Operators
Python's six comparison operators cover every possible relationship between two values. Each
returns True or
False and can be used directly in any boolean context —
if, while,
and/or, comprehensions,
and more.
a, b = 10, 20
# == Equal to
print(a == b) # False — 10 is not equal to 20
print(5 == 5) # True
print("hi" == "hi") # True — strings compared by value
# != Not equal to
print(a != b) # True
print(5 != 5) # False
# < Less than
print(a < b) # True — 10 < 20
print(20 < 10) # False
# > Greater than
print(a > b) # False — 10 > 20
print(20 > 10) # True
# <= Less than or equal to
print(10 <= 10) # True — equal satisfies <=
print(11 <= 10) # False
# >= Greater than or equal to
print(10 >= 10) # True
print(9 >= 10) # False
# Result is a bool — can use in arithmetic!
print(type(a == b)) # <class 'bool'>
print(int(a < b)) # 1 (True → 1)
nums = [-3, 0, 5, -1, 8]
print(sum(n > 0 for n in nums)) # 2 — counts positives
| Operator | Name | Example | Result | Description |
|---|---|---|---|---|
== |
Equal to | 5 == 5 |
True |
Values are the same |
!= |
Not equal to | 5 != 3 |
True |
Values are different |
< |
Less than | 3 < 5 |
True |
Left is smaller |
> |
Greater than | 5 > 3 |
True |
Left is larger |
<= |
Less than or equal | 5 <= 5 |
True |
Left is smaller or equal |
>= |
Greater than or equal | 5 >= 3 |
True |
Left is larger or equal |
Chained Comparisons — Python's Superpower
Python uniquely supports chained comparisons — you can combine multiple
comparison operators in a single expression, exactly like mathematical notation. The chain
evaluates left-to-right, and each adjacent pair is checked. If any pair is
False, the whole chain short-circuits to
False.
x = 15
# Chained comparison — reads like math!
print(10 < x < 20) # True — x is between 10 and 20
print(1 <= x <= 10) # False — x is not ≤ 10
print(10 < x <= 15) # True — x equals 15 (satisfies ≤)
# Equivalent to using 'and' — chaining is cleaner
print(10 < x and x < 20) # True — same result, more verbose
# Mixed operators in a chain
print(5 < x == 15) # True — 5<15 AND 15==15
print(1 < 2 < 3 < 4) # True — all adjacent pairs hold
print(1 < 2 > 0 == 0) # True — 1<2 AND 2>0 AND 0==0
print(1 < 2 < 2) # False — 2<2 is False
# Short-circuit: middle value evaluated once
def get_val():
print("evaluated!")
return 5
print(1 < get_val() < 10)
# evaluated! ← called only ONCE even in chain
# True
# Real-world: range check for user input
age = 22
if 18 <= age < 65:
print("Working age") # Working age
x > 1 && x < 10.
Python's 1 < x < 10 is not only shorter — it also
evaluates x only once, which matters if
x
is an expensive function call.
Comparing Strings
Python compares strings lexicographically (dictionary order) using Unicode code points. Each character is compared left-to-right; the first differing character determines the result. This means string comparison is case-sensitive by default — uppercase letters have lower code points than their lowercase equivalents.
# Equality
print("apple" == "apple") # True
print("Apple" == "apple") # False — case-sensitive!
print("apple" != "banana") # True
# Lexicographic ordering
print("apple" < "banana") # True — 'a' (97) < 'b' (98)
print("banana" > "apple") # True
print("abc" < "abd") # True — first 2 chars equal, 'c'<'d'
print("abc" < "abcd") # True — shorter string is "less"
# Case matters — uppercase < lowercase in ASCII
print("Z" < "a") # True — ord('Z')=90, ord('a')=97
print(ord("A"), ord("a")) # 65 97
# Case-insensitive comparison — use .lower() or .casefold()
s1, s2 = "Python", "python"
print(s1 == s2) # False — case-sensitive
print(s1.lower() == s2.lower()) # True — normalised
print(s1.casefold() == s2.casefold()) # True (better for unicode)
# Sorting strings uses comparison under the hood
words = ["banana", "apple", "cherry"]
print(sorted(words))
# ['apple', 'banana', 'cherry']
ord() returns the Unicode code point of a character.
Python's string comparison uses these points, so
"Z" < "a" because
ord("Z") = 90 <
ord("a") = 97.
.lower() for international text —
handles special cases like the German ß → ss. Prefer
casefold() for robust case-insensitive comparison.
Comparing Lists, Tuples & Other Sequences
Python compares lists and tuples element-by-element, left-to-right — the same lexicographic approach as strings. The first differing element determines the result. If all elements are equal up to the shorter sequence's length, the shorter one is considered "less than" the longer one.
# List equality — compares all elements
print([1, 2, 3] == [1, 2, 3]) # True
print([1, 2, 3] == [1, 2, 4]) # False — last element differs
print([1, 2] == [1, 2, 3]) # False — different lengths
# Lexicographic ordering for lists
print([1, 2, 3] < [1, 2, 4]) # True — 3 < 4 at index 2
print([1, 2] < [1, 2, 3]) # True — shorter is "less"
print([2, 0] > [1, 9, 9]) # True — 2>1 at index 0, rest ignored
# Tuple comparison — same rules
print((1, 2) == (1, 2)) # True
print((1, 2) < (1, 3)) # True
# Useful pattern: compare tuples for multi-key sorting
students = [("Alice", 90), ("Bob", 85), ("Carol", 90)]
students.sort() # sorts by name first, then score
print(students)
# [('Alice', 90), ('Bob', 85), ('Carol', 90)]
# Sort by score descending, then name ascending
students.sort(key=lambda s: (-s[1], s[0]))
print(students)
# [('Alice', 90), ('Carol', 90), ('Bob', 85)]
The Float Comparison Pitfall
Floating-point numbers are stored in binary (IEEE 754). Most decimal fractions cannot be
represented exactly in binary, leading to tiny rounding errors. This means comparing
floats with == can produce surprising
False results — and this affects
every language using IEEE 754, not just Python.
# ❌ The famous float comparison bug
print(0.1 + 0.2) # 0.30000000000000004 (!)
print(0.1 + 0.2 == 0.3) # False — IEEE 754 artefact
# See the full precision
print(repr(0.1)) # 0.1 (display truncated)
print(f"{0.1:.20f}") # 0.10000000000000000555...
# ✅ Fix 1: math.isclose() — recommended for most cases
import math
print(math.isclose(0.1 + 0.2, 0.3)) # True
print(math.isclose(1.0, 1.0000000001)) # True (within tolerance)
print(math.isclose(1.0, 1.01)) # False (too different)
# isclose signature: rel_tol=1e-9, abs_tol=0.0
print(math.isclose(0.0, 0.0000001, abs_tol=1e-6)) # True
# ✅ Fix 2: round() before comparing
print(round(0.1 + 0.2, 10) == round(0.3, 10)) # True
# ✅ Fix 3: Decimal module — exact decimal arithmetic
from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3")) # True
# ✅ Fix 4: use integers (multiply by 100 for currency)
print(10 + 20 == 30) # True — integers are always exact
math.isclose(a, b) for float equality checks. Use
the decimal.Decimal module for financial/currency
calculations where exact precision is required.
Mixed Types, == vs is & None Comparisons
Python allows cross-type comparisons in some cases and raises
TypeError in others. Understanding when types can and cannot
be compared — and the difference between == (value equality)
and is (identity) — prevents common bugs.
# ✅ int vs float — allowed (numeric promotion)
print(1 == 1.0) # True — 1 (int) equals 1.0 (float)
print(5 > 4.9) # True
print(True == 1) # True — bool is a subclass of int
print(False== 0) # True
print(True == 1.0) # True — numeric comparison
# ❌ str vs int — NOT allowed with < > (TypeError)
# print("5" > 3) → TypeError: '>' not supported between str and int
print("5" == 5) # False — different types, never equal
# == vs is — value vs identity
a = [1, 2, 3]
b = [1, 2, 3] # same VALUE, different object
c = a # same OBJECT
print(a == b) # True — same value
print(a is b) # False — different objects in memory
print(a is c) # True — same object
# None comparison — always use 'is', never ==
result = None
if result is None: # ✅ correct (PEP 8)
print("No result")
if result == None: # ⚠️ works but PEP 8 warns against it
print("No result")
# CPython integer caching (-5 to 256) — a common gotcha
x, y = 256, 256
print(x is y) # True — cached same object
x, y = 257, 257
print(x is y) # False — outside cache, new objects
print(x == y) # True — values still equal
| Comparison | Result | Why |
|---|---|---|
1 == 1.0 |
True |
Numeric promotion: int and float compared as numbers |
True == 1 |
True |
bool is a subclass of int; True equals 1 |
"5" == 5 |
False |
Different types — str and int are never equal |
"5" > 3 |
TypeError |
Ordering not defined between str and int |
[1,2] == [1,2] |
True |
Lists compared element-by-element |
[1,2] is [1,2] |
False |
Different objects in memory |
Practice Python Online — Free Compilers
Don't want to install anything yet? Practice all comparison operator examples from this chapter directly in your browser with these free Python environments.
-
Python has six comparison operators:
==,!=,<,>,<=,>=. All return abool. -
Chained comparisons like
1 < x < 10are valid Python — equivalent to1 < x and x < 10but evaluate the middle expression only once. -
String comparison is lexicographic (character-by-character Unicode order).
It is case-sensitive by default. Use
.casefold()for robust case-insensitive comparison. - List and tuple comparison is element-by-element from left to right. The shorter sequence is "less than" if all its elements match the longer one.
-
Float equality bug:
0.1 + 0.2 == 0.3isFalsedue to IEEE 754. Always usemath.isclose()for float comparisons. -
int vs float comparisons work via numeric promotion (
1 == 1.0isTrue). Comparingstrwithintusing<or>raisesTypeError. -
== checks value (calls
__eq__); is checks identity (same memory address). Always useis None, never== None. -
Comparison results are
boolwhich is a subclass ofint— use this to count:sum(x > 0 for x in nums)counts positive values.
Chained comparisons allow you to link multiple comparison
operators in a single expression, exactly like mathematical notation:
1 < x < 10. Python evaluates this as
1 < x and x < 10, checking each
adjacent pair left-to-right with short-circuit evaluation.
They are better than using explicit and in
two ways: (1) Readability —
1 < x < 10
reads like natural mathematical notation and is instantly understandable. (2)
Efficiency — the middle expression
x is evaluated only once, even if
it's a function call. With
f() > 0 and f() < 10, the function is
called twice; with 0 < f() < 10, it's
called once.
Python's float type uses
IEEE 754 double-precision binary format. Most decimal fractions
cannot be represented exactly in binary — just as 1/3 cannot be written exactly
in decimal. The stored value of 0.1 is
actually
0.1000000000000000055511151231257827021181583404541015625.
When you add 0.1 + 0.2, the rounding
errors accumulate, giving
0.30000000000000004 — not exactly
0.3. The correct solutions are:
math.isclose(0.1+0.2, 0.3) for
tolerance-based comparison, round() for
display rounding, or decimal.Decimal for
exact arithmetic.
Python compares strings lexicographically — character by
character from left to right, using each character's Unicode code point (ord()
value). The first differing character determines the result. Yes, comparison is
case-sensitive: uppercase letters have lower code points than
lowercase (ord("A") = 65,
ord("a") = 97), so
"Z" < "a" is
True. For case-insensitive comparison, use
s1.casefold() == s2.casefold() —
casefold() is preferred over
lower() because it handles international
Unicode edge cases like the German ß.
== is the
equality operator — it checks if two objects have the same
value by calling the object's
__eq__() method.
is is the
identity operator — it checks if two variables point to the
exact same object in memory (same
id()).
-
Use
==to compare values: numbers, strings, list contents. -
Use
isonly to check for singletons:is None,is True,is False. -
Never use
== None— PEP 8 requiresis None. -
Never rely on
isfor integers outside the CPython cache (-5 to 256) —257 is 257may beFalse.
Python compares lists (and tuples) lexicographically — element by element from index 0. It compares the first pair; if they're equal, it moves to the next pair, and so on. The first unequal pair determines the result.
For [2, 0] > [1, 9, 9]: Python compares
index 0 first — 2 > 1 is
True. Since the first elements already
differ, Python immediately returns
True without even looking at
9, 9 or the length difference. This is why
[2, 0] > [1, 9, 9] is
True — the first element wins.
1 < 2 < 3 return in Python?
"Z" < "a" return in Python?
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.