Convert List of booleans to List of integers in Python

This tutorial will discuss about unique ways to convert list of booleans to list of integers in Python.

Table Of Contents

Introduction

Suppose we have a list of booleans containing only False and True values. Like this,

listOfBools = [True, False, False, True, True, False]

Now we want to convert this list of bools to a list of 1s and 0s. Like this,

[1, 0, 0, 1, 1, 0]
  • The False should be converted to 0.
  • The True should be converted to 1.

Let’s how to do this.

Method 1: Using List Comprehension

Iterate over boolean elements of list, inside a List Comprehension, and call the int() method on each boolean element in the list. The int() method will convert boolean False to 0, and True to 1. The List comprehension, will returned a new list containing these converted int values.

Let’s see the complete example,

listOfBools = [True, False, False, True, True, False]

# Convert list of bools to list of integers
listOfInts = [int(elem) for elem in listOfBools]

print(listOfInts)

Output

[1, 0, 0, 1, 1, 0]

Method 2: Using NumPy Array

Create a NumPy Array from list of bools, but pass the dtype as int while constructing the NumPy Array. The array will have integers only i.e.

  • The False will be converted to 0.
  • The True will be converted to 1.

Then convert this NumPy array to a list of integers.

Let’s see the complete example,

import numpy as np

listOfBools = [True, False, False, True, True, False]

# create a NumPy Array of int type from list of bools
arr = np.array(listOfBools, dtype=int)

# Convert numpy array of ints to a list
listOfInts = arr.tolist()

print(listOfInts)

Output

[1, 0, 0, 1, 1, 0]

Summary

We learned about two different ways to convert a list of True and False to a list of 1s and 0s in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top