Python Reference ยท Built-in Functions
Python bool() function
Reference for Python bool(): convert any value to True or False, the list of falsy values, how __bool__ and __len__ decide truthiness, and common traps.
bool is the Boolean type, and calling bool(x) converts any value to either True or False using Python's truth-testing rules. It is the same test that if x: and while x: apply implicitly.
With no argument, bool() returns False. bool is a subclass of int, with exactly two instances: True (equal to 1) and False (equal to 0).
bool(0) # False bool("hello") # True
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.
Syntax
bool() bool(x)
| Name | Description |
|---|---|
x |
Optional. Any object. Positional only. |
Return value: False if x is a falsy value or no argument is given, otherwise True.
Raises: nothing for ordinary objects. Errors raised by a custom __bool__() or __len__() propagate, and __bool__() must return a real bool.
Usage notes
- Falsy values.
None,False, zero of any numeric type (0,0.0,0j,Decimal(0),Fraction(0, 1)), and empty sequences and collections ("",[],(),{},set(),range(0)). Everything else is truthy by default. - Non-empty strings are always truthy, including
"0"and"False". To parse text, compare it:text.lower() == "true". - Custom classes. Python calls
__bool__()first. If it is missing, it calls__len__()and treats0as false. With neither method, instances are always truthy. - No need for
bool()in conditions. Writeif items:rather thanif bool(items):orif len(items) > 0:. Usebool()when you need a stored value, such as a flag. andandorreturn operands, not booleans:"" or "default"is"default". Wrap inbool()only if you needTrue/False.- Identity vs truth. Test for
Nonewithis None, because0and[]are also falsy. - Not subclassable.
class Flag(bool)raisesTypeError. - NumPy arrays and pandas objects raise
ValueErrorwhen truth-tested if they have more than one element; use.any()or.all().