In Python, bool()
is a built-in function used to convert a value to bool
type. The bool()
function returns one of two values: True
or False
.
The bool()
function can accept any type of data as argument. It returns False
when the argument is:
- False
- 0 (including 0L and 0.0)
- Empty strings '', empty lists [], empty dictionaries {}, empty tuples (), empty sets set()
- None
All other values will be converted to True
, including non-empty strings, non-empty lists, non-empty dictionaries, non-empty tuples, non-empty sets, non-zero numbers, and non-empty objects.
For example:
print(bool(0)) # False
print(bool(3.14)) # True
print(bool('')) # False
print(bool('abc')) # True
print(bool([])) # False
print(bool([1,2,3])) # True
print(bool({})) # False
print(bool({'a':1})) # True
print(bool(())) # False
print(bool((1,2,3))) # True
print(bool(set())) # False
print(bool({1,2,3})) # True
print(bool(None)) # False
Note that the bool()
function doesn't forcefully convert the argument to bool
type, but rather returns the appropriate result based on the argument's type and value.