Python Reference ยท Numbers and Binary Data
Python comparison operators
Reference for Python comparison operators: ==, !=, <, <=, >, >=, chained comparisons, comparing different types, sequences and the difference between == and is.
Comparison operators test how two values relate and return a bool. Python has six value comparisons (==, !=, <, <=, >, >=) and the identity operators is and is not, which ask whether two names refer to the very same object.
Python also lets you chain comparisons: 1 < x < 10 means 1 < x and x < 10, with x evaluated only once.
3 == 3.0 # True "a" < "b" # True 1 < 5 < 10 # True
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
| Operator | Meaning |
|---|---|
a == b |
Equal values |
a != b |
Not equal |
a < b, a <= b |
Less than, less than or equal |
a > b, a >= b |
Greater than, greater than or equal |
a is b, a is not b |
Same object (identity), or not |
a < b < c |
Chained: a < b and b < c |
Return value: True or False for built-in types; custom classes can return anything from __eq__, __lt__ and the other special methods.
Raises: TypeError when ordering operators are used on types that cannot be compared, such as int and str. == and != never raise for built-ins.
Usage notes
==compares values,iscompares identity. Two equal lists are different objects. Useisonly for singletons:x is None,x is True.- Chaining short-circuits. In
a < b < c, ifa < bis false,cis not evaluated. The middle operand is evaluated once. - Strings compare by Unicode code point, character by character, so
"Z" < "a"and"10" < "9". For case-insensitive or language-aware ordering, use akeyfunction. - Sequences compare lexicographically: first differing items decide; a shorter sequence that is a prefix is smaller. A list never equals a tuple.
- Sets use subset ordering:
<=means subset, so two unrelated sets are neither<nor>nor equal. Not every pair of sets is ordered. float('nan')is not equal to anything, including itself. Test withmath.isnan().- Numbers of different types compare by value:
1 == 1.0 == True. - Custom classes get ordering from
__lt__and friends, or fromfunctools.total_orderingor a dataclass withorder=True.