Skip to content
Tutorials Center
My learning

Topics

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).

Python
bool(0)        # False
bool("hello")  # True

Try it

Python What is truthy and what is falsy?

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.

Python Making your own class truthy or falsy

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

Python
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 treats 0 as false. With neither method, instances are always truthy.
  • No need for bool() in conditions. Write if items: rather than if bool(items): or if len(items) > 0:. Use bool() when you need a stored value, such as a flag.
  • and and or return operands, not booleans: "" or "default" is "default". Wrap in bool() only if you need True/False.
  • Identity vs truth. Test for None with is None, because 0 and [] are also falsy.
  • Not subclassable. class Flag(bool) raises TypeError.
  • NumPy arrays and pandas objects raise ValueError when truth-tested if they have more than one element; use .any() or .all().