Python Comparison Operators
What you will learn
- The six comparison operators and the boolean they return
- The difference between
==and= - How numbers, text, lists and tuples are compared
- Why comparing the wrong types gives a
TypeError - Two cautions: floats and
nan
1. The six comparison operators
A comparison asks a yes-or-no question about two values, and answers with a boolean, True or False (lesson 2.3):
| Operator | Question | Example | Result |
|---|---|---|---|
== |
equal? | 5 == 5 |
True |
!= |
not equal? | 5 != 5 |
False |
< |
less than? | 5 < 7 |
True |
> |
greater than? | 5 > 7 |
False |
<= |
less than or equal? | 5 <= 5 |
True |
>= |
greater than or equal? | 5 >= 6 |
False |
print(5 == 5, 5 != 5, 5 < 7, 5 > 7, 5 <= 5, 5 >= 6)
True False True False True False
You can store the answer in a name like any other value: is_adult = age >= 18.
Quick check: is `x = 5` a comparison?
No. A single = stores a value. The comparison is x == 5.
2. == is not =
This is the most common beginner mistake:
| Symbol | Meaning |
|---|---|
= |
assign: store a value in a name |
== |
compare: are the two values equal? |
Python helps you: using = where a comparison is needed is a syntax error.
if x = 5:
print("five")
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
3. Comparing numbers
int and float compare by their value, even though they are different types. A bool also counts as 1 or 0 (lesson 2.3):
print(5 == 5.0, 1 == True, 0 == False)
print(True > False, sorted([True, False, True]))
True True True
True [False, True, True]
The surprising result of float calculations (lesson 3.4) applies here too: 0.1 + 0.2 == 0.3 is False. Compare floats from calculations with math.isclose, or check that the difference is tiny:
print(0.1 + 0.2 == 0.3)
print(abs((0.1 + 0.2) - 0.3) < 1e-9)
False
True
4. Comparing text
Strings compare by their characters' code numbers (lesson 4.1), so capitals come first, and the comparison is case-sensitive:
print("apple" < "banana", "Z" < "a", "a" < "B")
print("abc" < "abd", "abc" < "abcd", "" < "a")
print("apple" == "Apple")
True True False
True True True
False
Two strings are compared left to right, one character at a time, until they differ. A shorter string that is the beginning of a longer one comes first, and the empty string comes before everything.
Numbers stored as text are compared as text:
print("10" < "9", int("10") < int("9"))
print(10 == "10", str(10) == "10")
True False
False True
To compare numbers that came from input(), convert them first (lesson 2.5).
5. Comparing lists and tuples
Lists and tuples compare item by item from the left, just like text:
print([1, 2, 3] < [1, 2, 4])
print([1, 2] < [1, 2, 0])
print((1, 2) < (1, 3), ("b", 1) > ("a", 9))
print([1, 2] == [1, 2], [1, 2] == (1, 2))
True
True
True True
True False
[1, 2, 3] < [1, 2, 4]: the first difference is3against4.[1, 2] < [1, 2, 0]: the shorter one, being a start of the longer one, is smaller.[1, 2] == (1, 2)isFalse: a list is never equal to a tuple.
Sets compare by subset: {1, 2} < {1, 2, 3} is True because the first is a proper subset of the second. Two dictionaries are == when they have the same keys and values.
6. Comparing different types
== is happy to compare anything; different types are simply not equal. The order operators <, >, <=, >= refuse when there is no sensible order:
print(1 == "1")
1 < "2"
False
TypeError: '<' not supported between instances of 'int' and 'str'
The same happens for None < 1, [1] < (1,) and {1} < [1]. The fix is to convert one side so that the types match.
7. A caution about nan
The special value nan (lesson 3.1) is not equal to anything, even itself. All comparisons with it are false, except !=:
nan = float("nan")
print(nan == nan, nan != nan, nan < 1, nan > 1)
False True False False
Use math.isnan(x) to test for it.
8. Other tests that give booleans
Two more operators give booleans, and you will use them in conditions all the time:
| Operator | Question | Example |
|---|---|---|
in / not in |
is it a member of a collection or text? | 5 in [1, 5] is True |
is / is not |
is it the very same object? | x is None |
Remember the rule from lesson 2.6: compare values with ==, and use is only for None.
Worked example: can this person ride?
A ride needs a minimum height of 120 and a maximum of 190 (centimetres, made-up limits). Check a visitor who is 150 tall and 9 years old, and the ride's age limit is 8.
height = 150
age = 9
tall_enough = height >= 120
not_too_tall = height <= 190
old_enough = age >= 8
print(tall_enough, not_too_tall, old_enough)
True True True
| Check | Comparison | Result |
|---|---|---|
| tall enough | 150 >= 120 |
True |
| not too tall | 150 <= 190 |
True |
| old enough | 9 >= 8 |
True |
Lesson 5.3 shows how to combine the three answers into one with and.
Common mistakes
- Writing
=instead of==. - Comparing numbers stored as text (
"10" < "9"isTrue). - Using
==on floats from calculations. Usemath.isclose. - Comparing
Noneor different types with<, which gives aTypeError. - Expecting a list to equal a tuple.
- Testing for
nanwith==.
Key takeaways
==,!=,<,>,<=,>=returnTrueorFalse.=stores a value;==compares.- Text compares by character codes, left to right; lists and tuples compare item by item.
- Order comparisons between unrelated types raise
TypeError;==just givesFalse. - Take care with floats (use
isclose) andnan(useisnan).
Practice
1. What do 7 > 3, 7 == 3 and 7 != 3 give?
Show answer
True, False and True.
2. Why is "banana" < "cherry" true?
Show answer
The first characters differ (b against c), and b comes before c in the code table.
3. What do [2, 5] < [2, 7] and (1, 9) < (2, 0) give?
Show answer
Both are True. The first difference decides: 5 < 7 in the first, and 1 < 2 in the second.
4. What error does 5 < "5" cause, and how do you fix it?
Show answer
TypeError: '<' not supported between instances of 'int' and 'str'. Convert one side, for example 5 < int("5").
5. Write a comparison that is true when score is at least 50.
Show answer
score >= 50.
6. Write the safe way to check that two floats a and b from calculations are equal.
Show answer
math.isclose(a, b), after import math.