Skip to main content

Python Comparison Operators

Satellite · Operators

Python Comparison Operators

Operators that return Booleans feed your control flow. Understand how Python compares numbers, strings, containers, and custom objects.

Equality vs inequality

users_a = ["amy", "jo"]
users_b = ["amy", "jo"]

users_a == users_b # True
users_a != users_b # False

== compares values; override __eq__ on classes to customize behavior.

Ordering

<, >, <=, >= work on comparable types (numbers, strings). Strings compare lexicographically.

Identity

a = []
b = []
a is b # False
a is a # True

Use is only for singletons like None or Ellipsis.

Membership

"py" in "python"           # True
42 in {40, 41, 42} # True
"id" in {"id": 1} # True (checks keys)

Chained comparisons

0 < score <= 100 is equivalent to 0 < score and score <= 100. Python evaluates once per operand, making chained comparisons efficient and clean.

Next up in your learning path