Beginner Chapter 22 · 25 min read · Module 2: Operators and Expressions
Comparison Operators
- After this chapter you can use ==, !=, <, >, <= and >= correctly.
- You can explain that comparisons produce True or False values.
- You can write chained comparisons such as 0 < x < 10.
- You can compare strings and lists and predict the result.
- You can explain the difference between == and is.
Programs make decisions, and every decision starts with a question: is this number bigger than that one, is this password equal to the saved one, is the age at least 18? Comparison operators are the tools that ask these questions. Each comparison looks at two values and answers with a Boolean value, either True or False.
Python has six comparison operators. They are easy to type but have a few details that matter: a single = is not a comparison, strings are compared letter by letter, and a chain such as 1 < x < 5 is allowed. There are also two special operators, is and is not, which ask a different question from ==.
In this chapter you will use all six operators on numbers, strings and lists, learn how chained comparisons work, see the problems that float numbers can cause, and learn when to use == and when to use is.
The six comparison operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
| == | equal to | 5 == 5 | True |
| != | not equal to | 5 != 3 | True |
| < | less than | 3 < 2 | False |
| > | greater than | 3 > 2 | True |
| <= | less than or equal to | 4 <= 4 | True |
| >= | greater than or equal to | 3 >= 4 | False |
Every comparison gives back a value of type bool. That value can be printed, stored in a variable, or used directly in an if statement. Because True and False behave like 1 and 0 in arithmetic, True + True is 2, but you should rarely need that.
The most common beginner mistake is to confuse = with ==. A single = assigns a value to a name. A double == asks whether two values are equal. Writing if x = 5: is a syntax error in Python, which protects you from a bug that is common in some other languages.
a = 10
b = 7
print(a == b)
print(a != b)
print(a < b)
print(a > b)
print(a <= 10)
print(b >= 8)Comparing different kinds of values
Numbers are compared by value, and an int and a float can be compared directly, so 3 == 3.0 is True. Strings are compared one character at a time using each character's Unicode code number. This means "apple" < "banana" is True because a comes before b. Capital letters have smaller code numbers than small letters, so "Zebra" < "apple" is True too. To compare text without caring about case, convert both sides with .lower() first.
Lists and tuples are compared item by item from the left. The first position where the items differ decides the result. If one sequence is the start of the other, the shorter one is smaller. Comparing different types that cannot be ordered, such as 3 < "3", raises a TypeError, although 3 == "3" is simply False.
print(3 == 3.0)
print("apple" < "banana")
print("Zebra" < "apple")
print("Python".lower() == "python")
print([1, 2, 3] < [1, 2, 4])
print([1, 2] < [1, 2, 0])
print(3 == "3")Chained comparisons
Python lets you write several comparisons in a row. The expression 0 < x < 10 means 0 < x and x < 10, and it reads like mathematics. Python evaluates the middle value only once, which is neat when the middle part is a function call. Chains can use any mix of the six operators, but keep them short so that they stay readable.
age = 25
print(18 <= age < 65)
x = 5
print(0 < x < 3)
print(1 < 2 < 3 < 4)
print(1 == 1 != 2)
score = 82
if 80 <= score <= 100:
print("Grade A")== versus is, and floating point care
The operator == checks whether two values are equal. The operator is checks whether two names refer to the very same object in memory. Two different lists with the same items are equal but they are not the same object. Use is mainly for None, as in if x is None:. For numbers and strings always use ==, because whether two equal values are also the same object is an internal detail that you should not depend on.
Floats need extra care. Because numbers like 0.1 are stored approximately, 0.1 + 0.2 == 0.3 is False. Compare floats with round() or with math.isclose(), which allows a tiny difference. You should also remember that any comparison with float('nan') is False, even nan == nan.
import math
a = [1, 2]
b = [1, 2]
c = a
print(a == b)
print(a is b)
print(a is c)
x = None
print(x is None)
print(0.1 + 0.2 == 0.3)
print(math.isclose(0.1 + 0.2, 0.3))word = input()
if word.lower() == "yes":
print("Confirmed")
else:
print("Not confirmed")Python syntax
result = a == b # also !=, <, >, <=, >=low < value < high # chained comparisonif x is None: # identity checkReal-world applications
- Checking login details and passwords.
- Validating that an age or a score is in a legal range.
- Sorting and searching, which compare items again and again.
- Controlling loops, such as while count < 10.
- Filtering data, such as prices above a limit.
Common mistakes
Fix: Use == to compare. Python raises a SyntaxError for if x = 5, so read the error carefully.
Fix: Use math.isclose() or round() because floats are stored approximately.
Fix: Use == for values. Keep is for None and for checking the same object.
Fix: Convert both sides with .lower() or .casefold() before comparing.
Fix: input() returns a string. Convert it with int() first, otherwise you get a TypeError.
Important tips
- Read a chained comparison out loud, like 0 < x < 10, to check it.
- Use x is None rather than x == None.
- Use parentheses when mixing comparisons with and/or to make the meaning clear.
- Convert input() to a number before comparing numerically.
- Use math.isclose() when comparing results of float calculations.
Key points summary
- Six comparison operators: == != < > <= >=.
- Every comparison returns True or False.
- = assigns, == compares.
- Strings compare by character code, left to right.
- Lists and tuples compare item by item.
- Chained comparisons like a < b < c are allowed.
- == tests equal values, is tests the same object.
Exam and interview points
- Comparison operators return bool values.
- == compares value, is compares identity.
- Chained comparison evaluates each middle value once.
- Strings compare by Unicode code point, so uppercase comes before lowercase.
- Comparing unordered types such as int and str with < gives TypeError.
- Any comparison with nan is False except !=.
Quick revision
- == != < > <= >= give True or False.
- = is assignment, == is comparison.
- a < b < c means a < b and b < c.
- Text is compared character by character.
- Use is only for None and same-object checks.
- Use isclose() for floats.
Frequently asked questions
What is the difference between = and ==?
= assigns a value to a name. == compares two values and gives True or False.
Can I compare a string and a number?
You can test them with == and != (they are never equal), but < and > raise a TypeError because the two types have no order.
What does 1 < 2 < 3 mean?
It means 1 < 2 and 2 < 3, so the answer is True. Each neighbouring pair is checked.
When should I use is instead of ==?
Use is when you want to know if two names refer to the exact same object, mainly for the check x is None. Use == for normal value comparison.
Practise this chapter
21 practice questions Take the chapter quiz