Python Reference ยท Practical Pages
Truth value testing in Python
Concept page on Python truth value testing: which values are falsy, how bool() decides, __bool__ and __len__, and common pitfalls with if x and None checks.
Anywhere Python needs a yes/no answer (an if, a while, not, and, or, a comprehension filter, any(), all()) it asks the object for its truth value. You do not need a comparison: if items: is true when the list has something in it. Values that count as true are called truthy, the others falsy.
The rule is simple: an object is truthy unless its class says otherwise. A handful of built-in values are falsy, and your own classes can opt in with __bool__ or __len__.
if name: # true for any non-empty string print("hello", name)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
The falsy values
The built-in objects that are falsy:
NoneandFalse- zero of any numeric type:
0,0.0,0j,Decimal(0),Fraction(0, 1) - empty sequences and collections:
"",b"",[],(),{},set(),frozenset(),range(0)
Everything else is truthy by default, including "0", "False", " ", [0], [[]] and float("nan"). A container is judged by whether it is empty, not by what it contains.
How Python decides
For bool(x) or if x: Python checks, in order:
- If the type defines
__bool__, call it. It must return a realbool, orTypeErroris raised. - Otherwise, if the type defines
__len__, the object is falsy when the length is0. - Otherwise the object is truthy.
Some standard types follow this too: datetime.timedelta(0) is falsy; a datetime.time is always truthy in modern Python (before 3.5 midnight was falsy); NumPy arrays with more than one element raise ValueError when you test them, so use .any() or .all().
Usage notes
- Prefer
if items:overif len(items) > 0:andif not items:overif items == []:. It is shorter, works for every container and matches PEP 8. - Check
Noneexplicitly withis None.if x:conflatesNone,0,""and[], which is a bug when0or an empty string is a valid value. - A default argument like
def f(limit=None): limit = limit or 10silently replaces a deliberate0. Writeif limit is None:instead. and/orreturn one of their operands and short-circuit: the right side is only evaluated when needed.bool(a or b)converts the result when you need a realTrue/False.- Comparison operators return real booleans;
==on two lists compares contents, so[] == FalseisFalseeven though both are falsy. TrueandFalseare instances ofint(True + True == 2), which is whysum()of booleans counts the true ones.
Related
- bool, any(), all()
- Logical operators,
__bool__ - The Python data model
- Tutorial lessons: Booleans, None, Comparison and logical operators