This tutorial will discuss about unique ways to convert list of 1s and 0s to a list of booleans in Python.
Table Of Contents
Introduction
Suppose we have a list of integers containing only 1s and 0s. Like this,
listOfNums = [1, 0, 1, 1, 0, 0, 0, 1]
Now we want to convert this list of 1s and 0s to a List of booleans. Like this,
[True, False, True, True, False, False, False, True]
- The 0 should be converted to False.
- The 1 should be converted to True.
Let’s how to do this.
Method 1: Using List Comprehension
Iterate over elements of list, inside a List Comprehension, and call the bool()
method on each element or number in the list. The bool()
method will convert number 0
to False
, and any other number to True
. The List comprehension, will returned a new list containing these converted boolean values.
Let’s see the complete example,
Frequently Asked:
listOfNums = [1, 0, 1, 1, 0, 0, 0, 1] # convert list of integers to list of bools listOfBools = [bool(elem) for elem in listOfNums] print(listOfBools)
Output
[True, False, True, True, False, False, False, True]
Method 2: Using NumPy Array
Create a NumPy Array
from list of numbers, but pass the dtype
as bool
while constructing the NumPy Array. The array will have bools only i.e.
- The
0
will be converted toFalse
. - Anyother number will be converted to
True
.
Then convert this NumPy array to a list of booleans.
Let’s see the complete example,
import numpy as np listOfNums = [1, 0, 1, 1, 0, 0, 0, 1] # create a NumPy Array of bool type from list arr = np.array(listOfNums, dtype=bool) # Convert numpy rray of bools to a Boolean list listOfBools = arr.tolist() print(listOfBools)
Output
[True, False, True, True, False, False, False, True]
Summary
We learned about two different ways to convert a list of 1s and 0s to list of bools in Python.