Python bool() built-in function

From the Python 3 documentation

Return a Boolean value, True or False. x is converted using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise, it returns True. The bool class is a subclass of int. It cannot be subclassed further. Its only instances are False and True.

Introduction

The bool() function in Python is a built-in function that converts a value to a Boolean (True or False). It follows the standard truth testing procedure, where values like 0, None, and empty collections are considered False, while most other values are True. This is fundamental for controlling the flow of your program with conditional statements.

Examples

Falsy Values

These values are considered False:

>>> bool(False)
# False
>>> bool(None)
# False
>>> bool(0)
# False
>>> bool(0.0)
# False
>>> bool('')      # empty string
# False
>>> bool([])      # empty list
# False
>>> bool({})      # empty dict
# False
>>> bool(set())   # empty set
# False

Truthy Values

Most other values are considered True:

>>> bool(True)
# True
>>> bool(1)
# True
>>> bool(-1)
# True
>>> bool('hello')
# True
>>> bool([1, 2])
# True
>>> bool({'a': 1})
# True

Subscribe to pythoncheatsheet.org

Join 16,702+ Python developers in a two times a month and bullshit free publication , full of interesting, relevant links.