Sub topic 2
Truthiness: what counts as true or false
This chapter assumes you know basic Python syntax (variables, functions, if statements) and the built-in types int, str, list, and dict. You have already met True and False. Here you learn how Python decides whether any object counts as true or false when a condition expects a boolean.
The truth value testing rule
Python lets you put any object where a condition is expected. The language defines a truth value for every object, and the test is called truth value testing, or truthiness. An object is truthy if it tests as true and falsy if it tests as false.
Truth value testing happens in these places:
- the condition of
if,elif, andwhile - the operand of
not - the operands of
andandor - the condition of a conditional expression (
a if cond else b) - the
ifclause of a comprehension - the
bool()constructor, which makes the result explicit
def describe(items):
if items:
return f"{len(items)} item(s)"
return "empty"
print(describe([])) # empty
print(describe(["a", "b"])) # 2 item(s)if items: is the idiomatic way to ask "does this container have anything in it?". It is shorter than if len(items) > 0: and works for lists, strings, dicts, sets, and tuples alike.
What is falsy
Built-in objects are falsy in exactly these cases:
| Category | Falsy values |
|---|---|
| Constants | `None`, `False` |
| Numeric zero | `0`, `0.0`, `0j`, `Decimal(0)`, `Fraction(0, 1)` |
| Empty sequences | `""`, `()`, `[]`, `range(0)`, `b""` |
| Empty collections | `{}`, `set()`, `frozenset()` |
| Your own classes | Objects whose `__bool__()` returns `False` or whose `__len__()` returns `0` |
Everything else is truthy. You can check every built-in in the table with one loop:
values = [None, False, 0, 0.0, 0j, "", (), [], {}, set(), range(0)]
for v in values:
print(repr(v), bool(v))
# Every line prints FalseMany truthy values surprise people the first time:
print(bool("0"), bool("False"), bool(" ")) # True True True
print(bool([0]), bool([[]]), bool({0: 0})) # True True True
print(bool(0.1), bool(float("nan"))) # True TrueThe rule is about emptiness and zero of the container or number itself, not about its contents. [0] has one element, so it is truthy even though that element is falsy. The string "0" has one character, so it is truthy. float("nan") is not zero, so it is truthy too.
A decision flow
The diagram shows the order in which Python checks an object. The next section explains the __bool__ and __len__ steps.
Numbers and built-in containers follow the same logic internally. Zero integers and empty containers are falsy because of their __bool__ or __len__ behavior.
How your own classes take part
For an object of your own class, Python first calls __bool__. If the class does not define it, Python calls __len__ and treats a length of zero as false. If the class defines neither, every instance is truthy.
class Basket:
def __init__(self, items):
self.items = list(items)
def __len__(self):
return len(self.items)
class Flag:
def __bool__(self):
return False
class Both:
def __len__(self):
return 5
def __bool__(self):
return False
print(bool(Basket([])), bool(Basket([1]))) # False True
print(bool(Flag())) # False
print(bool(Both())) # FalseBoth shows the priority: __bool__ wins even though __len__ returns 5. __bool__ must return a real bool, and __len__ must return a non-negative integer. Anything else raises TypeError. A later chapter returns to this topic along with __eq__.
Always-truthy objects that look empty
Some objects never become falsy, even when there is nothing left in them. Generators and other iterators do not define __len__ or __bool__, so they are always truthy.
gen = (n for n in [])
print(bool(gen)) # True
print(bool(list(gen))) # FalseIf you need to know whether an iterator produced anything, you must consume it (or use next(gen, sentinel)). Testing the generator object itself tells you nothing.
Third-party types can also differ from the built-in rules. A NumPy array with more than one element raises ValueError when used in an if, because "is any element true or all of them?" is ambiguous. Pandas objects do the same. For those types, read the library's documentation and use its explicit methods such as .any() and .all().
Producing an actual boolean
bool(x) converts any object to True or False using the rules above. not x also returns a real boolean, always the opposite of the truth value.
print(bool([]), not []) # False True
print(bool("hi"), not "hi") # True False
print(not not "hi") # TrueThe bool() form reads better than not not. In most if statements you need neither, because the condition is tested for truth already.
A related tool is filter(None, iterable). Passing None as the function keeps only the truthy items:
print(list(filter(None, [0, 1, "", "a", None, []]))) # [1, 'a']Common errors
Treating "falsy" as "missing"
The most frequent mistake is using a truth test when you mean "was a value provided?". Zero, the empty string, and the empty list are often valid values.
def volume_buggy(level=None):
if not level:
level = 50
return level
def volume(level=None):
if level is None:
level = 50
return level
print(volume_buggy(0)) # 50 (the user asked for silence and got 50)
print(volume(0)) # 0
print(volume()) # 50volume_buggy(0) overrides a legitimate 0. When the question is "was anything passed?", test with is None. Use plain truthiness only when every falsy value really should be treated the same way. The chapters on None cover the is None check in detail.
Comparing to `True` or `False`
Writing if flag == True: is redundant, and it is also wrong for values that are truthy but not equal to True:
items = [1, 2]
print(items == True) # False
if items:
print("truthy") # truthyitems == True asks whether the list equals True, which it never does. if items: asks whether the list is truthy. Write if flag: and if not flag:.
Strings that look like booleans
Text from files, environment variables, or input() is a str. Any non-empty string is truthy, including "0" and "False".
answer = "0"
print(bool(answer)) # True
print(bool(int(answer))) # FalseConvert the text to the right type first, for example int(answer), or compare against an explicit set of accepted strings such as answer.lower() in {"1", "true", "yes"}.
Assuming an empty result is `None`
A function that returns [] and one that returns None are both falsy, but they are not the same. If callers must tell them apart, use is None. If they do not need to, truthiness is fine and simpler. Decide which meaning you intend and keep it consistent in your API.
Summary of the rules
- Every object has a truth value. There are no values that raise an error in an
if, except types such as NumPy arrays that define their own rule. - Falsy built-ins are
None,False, numeric zeros, and empty sequences and collections. Everything else is truthy. - For your own classes,
__bool__is checked first, then__len__, and otherwise the instance is truthy. bool(x)andnot xgive you a realTrueorFalse.- A falsy value is not necessarily
None, andNoneis not the only way to say "no value".
Exercise
Predict the output of each line, then run the code to check. print(bool("False")) print(bool([[]])) print(bool(0.0) or bool("")) print(bool(x for x in []))
Show answer
The lines print True, True, False, and True. The string "False" is non-empty, so it is truthy. The list [[]] contains one element (an empty list), so the outer list is non-empty and truthy. 0.0 and "" are both falsy, so the or expression is False. The last line passes a generator expression, which is an object that never defines _bool or len_, so it is always truthy even though it would produce no items.
Exercise
The function below is meant to return the configured retry count, or 3 when no value was given. It should respect an explicit 0, which means "do not retry". Explain the bug and fix it. def retries(count=None): return count or 3
Show answer
count or 3 returns 3 whenever count is falsy, so an explicit 0 is replaced by 3. Test for None instead:
def retries(count=None):
if count is None:
return 3
return count
Now retries(0) returns 0, retries() returns 3, and retries(5) returns 5.