Convert a boolean to an integer in Python

avatar

Borislav Hadzhiev

Last updated: Aug 28, 2022

banner

Photo from Unsplash

Convert a boolean to an integer in Python #

Use the int() class to convert a boolean to an integer, e.g. my_int = int(my_bool). The int() class will convert True values to 1 and False values to 0.

main.py
import numpy as np # ✅ convert boolean to integer my_bool = True my_int = int(my_bool) print(my_int) # 👉️ 1 my_bool = False my_int = int(my_bool) print(my_int) # 👉️ 0 # ----------------------------------------------- # ✅ convert list of booleans to list of integers my_list = [False, False, True, True] result = [int(item) for item in my_list] print(result) # 👉️ [0, 0, 1, 1] # ----------------------------------------------- arr = np.array([False, False, True, True], dtype=bool) int_arr = arr.astype(int) print(int_arr) # 👉️ [0 0 1 1]

We used the int() class to convert True to 1 and False to 0.

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

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

The constructor returns 0 if no arguments are given.

True boolean values return 1 after conversion to integers and False values return 0.

If you need to convert a list of boolean values to a list of integers, use a list comprehension.

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

We used a list comprehension to iterate over the list.

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 boolean value to an integer and return the result.

If you need to convert a numpy array of booleans to an array of integers, use the numpy.astype() method.

main.py
import numpy as np arr = np.array([False, False, True, True], dtype=bool) int_arr = arr.astype(int) print(int_arr) # 👉️ [0 0 1 1]

You can use the astype method on a numpy array to copy the array and cast it to a specified type.

The only parameter we passed to the astype method is the data type to which the array is cast.

To convert the array of booleans to an array of integers, pass the int class to the astype() method.

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.