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. It covers how Python decides whether any object counts as true or false.
Truth value testing
An if or while condition does not have to be a bool. Python accepts any object and asks for its truth value. This is called truthiness. An object is truthy if Python treats it as true in a condition, and falsy if it treats it as false.
You can see the decision directly by calling bool() on a value:
print(bool([]), bool([0]), bool(""), bool("0"), bool(0.0), bool(None))
# False True False True False False[0] is truthy because the list has one element, even though that element is falsy. "0" is truthy because the string has one character.
The falsy values
Almost everything is truthy. The built-in falsy values are a short list:
| Falsy value | Type |
|---|---|
| `None` | `NoneType` |
| `False` | `bool` |
| `0`, `0.0`, `0j` | numbers |
| `""` | empty string |
| `[]`, `()`, `{}`, `set()`, `range(0)` | empty containers |
Every other built-in value is truthy. This includes non-empty containers and strings, and nonzero numbers (including negative ones).
Using truthiness in conditions
Truthiness lets you write short tests for emptiness:
items = []
if not items:
print("nothing to process")
name = "Ada"
if name:
print(f"Hello, {name}")This is the idiomatic way to test whether a container or string is empty. Writing if len(items) == 0: works, but it is longer and gains nothing.
Truthiness for your own classes
For instances of your own classes, Python checks two special methods in order:
__bool__, which should returnTrueorFalse.__len__, whose result is false when it is0.
If a 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
print(bool(Basket([])), bool(Basket([1]))) # False True
print(bool(Flag())) # FalseBasket gets its truth value from __len__, so an empty basket is falsy. Flag defines __bool__ directly, so it is always falsy.
Common errors
Truthiness is convenient, but it can hide a real distinction. These are the mistakes intermediate learners make most often.
- Treating "no value" and "empty or zero" as the same thing. A count of
0is falsy, but it is a real answer. IfNonemeans "not provided", testif value is None:. Chapter sections onNonecover this in detail. - Assuming a string that looks false is false.
bool("False")andbool("0")are bothTrue, because the strings are non-empty. If you read input as text, convert it before testing it. - Testing a custom object that defines
__len__. An object with__len__returning0is falsy, which may surprise a caller who only wanted to know whether the object exists.
def describe(count):
if not count:
return "missing or zero"
return f"{count} items"
print(describe(0)) # missing or zero
print(describe(None)) # missing or zero
print(describe(3)) # 3 itemsHere 0 and None get the same message. If they should be handled differently, truthiness is the wrong tool and an explicit check is needed.
Exercise
Predict the output of print(bool([[]]), bool({}), bool("False"), bool(-1)), and explain why the first value differs from bool([]).
Show answer
It prints True False True True. [[]] is a list with one element (an empty list), so it is non-empty and truthy, while [] has no elements and is falsy. {} is an empty dict, so it is falsy. "False" is a non-empty string and -1 is a nonzero number, so both are truthy.
Exercise
A class Queue stores its elements in self.items and defines only __len__. What does if queue: do when queue.items is empty, and how would you make the class always truthy regardless of length?
Show answer
The condition is false, because Python falls back to __len__ and sees 0. To make instances always truthy, define __bool__ returning True, since __bool__ is checked before __len__.