Sub topic 8
Truthiness of values
This chapter assumes you know Python's built-in types and how if statements work. It covers how Python turns any value into True or False.
What truthiness means
Conditions such as if and while, and the operators and, or and not, accept any object, not only booleans. Python asks each object whether it counts as true or false. A value that counts as false is called falsy. A value that counts as true is called truthy.
The built-in bool() function shows the answer directly.
values = [0, 0.0, "", [], {}, set(), None, False, "0", [0], " "]
for v in values:
print(repr(v), bool(v))The first eight values print False. The last three ("0", [0] and " ") print True, because each is a non-empty container or string.
The falsy values
| Kind | Falsy values |
|---|---|
| Constants | `None`, `False` |
| Numbers | `0`, `0.0`, `0j` |
| Empty sequences | `""`, `[]`, `()`, `range(0)` |
| Empty collections | `{}`, `set()` |
Nearly everything else is truthy. The rule of thumb is that "zero or empty" is falsy and "something is there" is truthy.
How Python decides for your own classes
For an instance of a class, Python checks two special methods in order:
__bool__, if defined. It must return a realbool.__len__, if defined. A length of0is falsy.
If the class defines neither, every instance is truthy.
class Basket:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
class Switch:
def __bool__(self):
return False
def __len__(self):
return 5
print(bool(Basket([])))
print(bool(Basket(["apple"])))
print(bool(Switch()))This prints False, True and False. Switch has a length of 5, but __bool__ takes priority.
Common errors
The most frequent mistake is using a truthiness test when you mean "was a value provided?". A legitimate 0 or empty list is falsy, so it gets treated as missing.
def pick_limit(limit=None):
return limit or 10
def pick_limit_fixed(limit=None):
return 10 if limit is None else limit
print(pick_limit(0))
print(pick_limit_fixed(0))The first call prints 10 and discards the caller's 0. The second prints 0. Use is None when None is the only value that means "missing".
Other points to watch:
- Prefer
if items:overif len(items) > 0:for sequences. It is shorter and works for any container. - Do not write
if flag == True:. Writeif flag:. The comparison also fails for truthy values that are not equal toTrue, such as2. - Some third-party types refuse a truth test. A NumPy array with more than one element raises a
ValueErrorinif arr:, so usearr.any()orarr.all(). boolis a subclass ofint, soTrue + Trueis2. This is a quirk of the number system, not of truthiness.
Exercise
What do bool(" ") and bool([[]]) return, and why?
Show answer
Both return True. The string " " contains one space, so it is not empty. The list [[]] contains one element (an empty list), so the outer list is not empty. Truthiness checks only whether the container itself is empty, not what is inside it.