Convert the numbers 1 and 0 to Boolean values in Python

avatar

Borislav Hadzhiev

Last updated: Aug 28, 2022

banner

Photo from Unsplash

Convert the numbers 1 and 0 to Boolean values in Python #

Use the bool() class to convert the numbers 1 and 0 to boolean values, e.g. result = bool(1). The bool() class will return True when converting 1 to a boolean and False when converting 0 to a boolean.

main.py
# ✅ convert 1 and 0 to boolean values result = bool(1) print(result) # 👉️ True result = bool(0) print(result) # 👉️ False # ------------------------------------------ # ✅ convert boolean values to integers result = int(True) print(result) # 👉️ 1 result = int(False) print(result) # 👉️ 0 # ------------------------------------------- # ✅ convert list of 1 and 0 to boolean values my_list = [1, 1, 0, 1] result = [bool(item) for item in my_list] print(result) # 👉️ [True, True, False, True]

We used the bool() class to convert the numbers 1 and 0 to booleans.

main.py
result = bool(1) print(result) # 👉️ True result = bool(0) print(result) # 👉️ False

The bool() class takes a value and converts it to a boolean (True or False). If the provided value is falsy or omitted, then bool returns False, otherwise it returns True.

All values that are not truthy are considered falsy. The falsy values in Python are:

  • constants defined to be falsy: None and False.
  • 0 (zero) of any numeric type.
  • empty sequences and collections: "" (empty string), () (empty tuple), [] (empty list), {} (empty dictionary), set() (empty set), range(0) (empty range).

The bool() class returns True if passed any non-falsy value.

In other words, the bool() class will return True when called with any number other than 0.

If you need to convert a boolean value to an integer, use the int() class.

main.py
result = int(True) print(result) # 👉️ 1 result = int(False) print(result) # 👉️ 0

The int class returns an integer object constructed from the provided number or string argument.

The constructor returns 0 if no arguments are given.

If you have a list of 1s and 0s and need to convert it to a list of booleans, use a list comprehension.

main.py
my_list = [1, 1, 0, 1] result = [bool(item) for item in my_list] print(result) # 👉️ [True, True, False, True]

We used a list comprehension to iterate over the list of numbers.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we convert the current value to a boolean and return the result.

The new list contains the boolean representation of the 1s and 0s.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.