Guide Python Beginner

7.4 Comparison Operators

Python's comparison operators — == != < > <= >= — comparison chaining, and comparing tuples lexicographically for version numbers.

2 min read

What Are They?

Operators that compare two values and always return a bool.

Why Are They Used?

The foundation of every conditional (if, while) in a program.

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
<Less than5 < 3False
>Greater than5 > 3True
<=Less than or equal5 <= 5True
>=Greater than or equal5 >= 6False

Comparison Chaining

What Is It?

Writing a < b < c evaluates as (a < b) and (b < c) — both comparisons must hold, and b is only evaluated once. Covered in more depth in 7.12 Chained Comparisons.

>>> 1 < 2 < 3
True

Version Comparison

What Is It?

Comparing tuples element-by-element — exactly how version numbers like (1, 5, 0) are typically compared, since Python compares tuples lexicographically (the first differing element decides the result).

>>> v1 = (1, 5, 0)
>>> v2 = (1, 4, 9)
>>> v1 > v2      # compares 1==1, then 5>4 decides it
True

Quick Interview Answer

“Comparison operators (== != < > <= >=) always return a bool and are the foundation of every if/while condition. Python allows chaining them directly — a < b < c — which evaluates as (a < b) and (b < c), with b evaluated only once. A practical use of comparison is comparing tuples lexicographically, which is exactly how version tuples like (1, 5, 0) are typically compared.”

Common Mistakes

  • Using == on floats expecting exact equality — floating-point rounding means 0.1 + 0.2 == 0.3 is False; compare with a tolerance instead (abs(a - b) < 1e-9).
  • Using is where == was intended — is compares identity, not value, covered fully in 7.8 Identity Operators.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form