How To Convert The Numbers 1 And 0 To Boolean Values In Python

In this article, we will show you how to convert the numbers 1 and 0 to Boolean values in Python. To do that, you can use the bool() function, the map() method, or the if condition. Let’s learn more about it with the explanation and example below.

Convert The Numbers 1 And 0 To Boolean Values In Python

Use the bool() function

To convert the numbers in an object to boolean values, you can use the bool() function combined with the list comprehension. The bool() function returns the boolean value from the current object.

Syntax

bool(object)

Parameters

  • object: An object

Return Value

False if the object is empty, 0, False, or None. Otherwise, True.

Look at the example below to learn more about this solution.

# A list contains numbers 1 and 0
numList = [0, 0, 0, 1, 0, 1, 1, 1, 0]
print('Numeric values: ' + str(numList))

# Convert it to the boolean values
boolList = [bool(x) for x in numList]
print('Boolean values: ' + str(boolList))

Output

Numeric values: [0, 0, 0, 1, 0, 1, 1, 1, 0]
Boolean values: [False, False, False, True, False, True, True, True, False]

Use the bool() function

To convert the numbers in an object to boolean values, you can use the bool() function combined with the map() method. 

Look at the example below to learn more about this solution.

# A list contains numbers 1 and 0
numList = [0, 0, 0, 1, 0, 1, 1, 1, 0]
print('Numeric values: ' + str(numList))

# Convert it to the boolean values
boolList = list(map(bool, numList))
print('Boolean values: ' + str(boolList))

Output

Numeric values: [0, 0, 0, 1, 0, 1, 1, 1, 0]
Boolean values: [False, False, False, True, False, True, True, True, False]

Use the if condition

To convert the numbers in an object to boolean values, you can use the if condition combined with the list comprehension.

Look at the example below.

# A list contains numbers 1 and 0
numList = [0, 0, 0, 1, 0, 1, 1, 1, 0]
print('Numeric values: ' + str(numList))

# Convert it to the boolean values
boolList = [False if x == 0 else True for x in numList]
print('Boolean values: ' + str(boolList))

Output

Numeric values: [0, 0, 0, 1, 0, 1, 1, 1, 0]
Boolean values: [False, False, False, True, False, True, True, True, False]

Summary

We have shown you how to convert the numbers 1 and 0 to Boolean values in Python. To do that, you can use the bool() function or the if condition combined with the map() method or the list comprehension. You should use the bool() method because it is fast and built-in Python to convert an object to a boolean value. 

Leave a Reply

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