Comparison and logical operators are how a program decides what to do. Python's versions have two habits that differ from most other languages. The and and or operators return one of their operands instead of True or False, and they stop early, so the right-hand side is never run when the answer is already known. Both of these are useful once you understand them, and both of them cause very confusing bugs when you do not. This lesson builds the idea up from the start.
The previous lesson in this module covered "if, elif, else: Writing Decisions That Read Cleanly", and the next lesson in this module is about "for Loops and range(): Iterating with Intention".
What comparison operators does Python have?
| Operator | Meaning | Example |
|---|---|---|
== != | equal, not equal | 3 == 3.0 is True |
< <= > >= | ordering | 2 <= 2 <= 4 is True |
is is not | same object in memory | value is None |
in not in | membership | 'a' in 'cat' |
and or not | combine conditions | a and b |
a, b = 10, 20
print('a == b ->', a == b)
print('a != b ->', a != b)
print('a < b ->', a < b)
print('a <= b ->', a <= b)
print('a > b ->', a > b)
print('a >= b ->', a >= b)
print('"b" in "abc" ->', 'b' in 'abc')
print('5 in [1, 2] ->', 5 in [1, 2])
print('"k" in {"k": 1} ->', 'k' in {'k': 1})
print('5 not in [1, 2] ->', 5 not in [1, 2])
Membership works on strings, lists, tuples, sets, and dictionaries. For a dictionary it checks the keys and not the values, which surprises people. 'k' in {'k': 1} is True because the key is there.
What do and, or and not actually return?
Here is the part that surprises most people. and and or do not turn their operands into booleans and then return a boolean. They return one of the operands, and they pick it using the truthiness of the first one.
a and breturnsawhenais falsy, and otherwise it returnsb.a or breturnsawhenais truthy, and otherwise it returnsb.not aalways returns a real boolean, which is the opposite of the truthiness ofa.
# and and or return one of their operands.
print('5 and 7 ->', 5 and 7)
print('0 and 7 ->', 0 and 7)
print('0 or 7 ->', 0 or 7)
print('5 or 7 ->', 5 or 7)
# not always returns a boolean.
print('not 0 ->', not 0)
print('not 5 ->', not 5)
def expensive():
print(' this line did NOT run')
return True
# The right side is skipped when the left side already decides.
print('True or expensive() ->', True or expensive())
print('False and expensive() ->', False and expensive())
Stopping early is not only about speed. It is a promise about what happens to the rest of the expression. If the left side already gives the answer, the right side never runs, so a function call on the right never happens at all. That is how you write a safe guard such as if user is not None and user.name == 'ada'. When the user is missing, the attribute is never read and no error is raised.
Returning an operand is useful when you want a default value. The line name = user_name or 'anonymous' gives you the user name when it is a non-empty string, and the fallback otherwise. It is also a trap, because x = a or b picks a whenever a is truthy, even when a is 0 and you meant the number zero.
How do chained comparisons work?
Python lets you chain comparisons, and the whole chain is checked as one unit instead of as a set of separate tests. 0 <= score <= 100 means "score is at least zero and score is at most 100", and the check stops at the first part that fails.
score = 75
print('0 <= score <= 100 ->', 0 <= score <= 100)
print('10 < 5 < 20 ->', 10 < 5 < 20)
a, b, c, d = 1, 1, 2, 2
print('a == b and c == d or a == c ->', a == b and c == d or a == c)
print('with brackets ->', (a == b and c == d) or (a == c))
names = ['ada', 'grace', 'alan']
print('all in list ->', all(name in names for name in ('ada', 'alan')))
The second group shows why brackets matter. Comparisons bind tighter than and and or, so a == b and c == d or a == c is read as (a == b and c == d) or (a == c). That is usually what people mean, but the line reads in a confusing way, and the moment you add an or in the middle the meaning changes. Brackets cost nothing and they remove the question entirely.
When should you use is instead of ==?
Equality compares the values that two objects hold. Identity asks whether two names point at the same object in memory. For most values both questions have the same answer, which is why == is the right default. There are two cases where identity is the better question to ask.
first = ['a']
second = ['a']
print('equal lists ->', first == second)
print('same object? ->', first is second)
value = None
print('value is None ->', value is None)
left = int('1000')
right = int('1000')
print('equal ints ->', left == right)
print('same object? ->', left is right)
Use is None and is not None whenever you are checking for a missing value. None is a singleton, so identity is exactly the right question, and == lets a class define equality in a way that changes your answer. The same goes for the special objects that libraries use to mean "no value supplied".
Never use is to compare numbers. Small integers are shared between programs, larger ones are not, and identical numbers inside the same file are often folded into a single object. So identity for numbers depends on details that you should never rely on. Compare them with == instead.
How do all() and any() differ from and and or?
all() returns True when every item in an iterable is truthy. any() returns True when at least one item is truthy. Both of them take a generator expression, so they can check a stream of values without building a list first, and both of them stop early.
numbers = [2, 4, 6]
print('all even ->', all(number % 2 == 0 for number in numbers))
print('any odd ->', any(number % 2 == 1 for number in numbers))
print('all of empty ->', all([]))
print('any of empty ->', any([]))
def is_positive(number):
print(' checking', number)
return number > 0
# any() stops at the first match.
print('any result ->', any(is_positive(number) for number in [-1, -2, 5, 6]))
Stopping early matters most when the checks are expensive. In the example above, any() stops after the third value because that value is positive, so the fourth one is never checked at all. The same trick works for validation. all() over a generator stops at the first problem, so you can report the first bad field instead of collecting every failure into a list.
There is a memory reason to prefer the generator form as well. all([x > 0 for x in values]) builds the whole list before all() looks at it. all(x > 0 for x in values) checks each item as it goes and throws it away straight away. For a long list, or for a check that costs real time, the generator keeps memory flat and stops early.
There are two edge cases to remember. all([]) is True and any([]) is False, because nothing failed and nothing succeeded. If your list can be empty and the answer matters, handle that case yourself.
Your turn: write a password policy validator
- Write
is_strong(password)that returnsTrueonly when the password is at least 12 characters long and has an uppercase letter, a lowercase letter, and a digit. Use a chained comparison for the length, andall()with a generator for the character classes. - Test it against a list of passwords, including one that is long enough but has no digit in it, and print each result.
- Now write the same checks with plain
andandor, and confirm that the two versions agree on every input. Add a comment that says why theall()version is easier to extend later. - Add a rule that rejects a password containing a space, using the
inoperator. Check that a password with a space is rejected even when every other rule passes. - Finish with
describe_failures(password), which returns a list of the rules that the password breaks. Use a list comprehension over a list of(rule_name, passed)pairs. That gives the user a useful message instead of a singleFalse.
Operator cheat sheet
andreturns its first falsy operand or its last one, andorreturns its first truthy operand or its last one.- Stopping early guarantees that the right-hand side is skipped when the answer is already known, and that is what makes guard conditions safe.
- A chained comparison such as
0 <= x <= 100is one expression and not two, and it stops at the first failure. - Comparisons bind tighter than
andandor, so add brackets when a condition mixes both of them. - Use
is Nonefor missing values,==for everything else, and neveristo compare numbers. all()andany()take generators, stop early, and treat an empty list asTrueandFalserespectively.