In Python True and False are equivalent to 1 and 0. Use the int() method on a boolean to get its int values.
x = True
y = False
print(int(x))
print(int(y))
Output:
int() turns the boolean into 1 or 0.
Note: that any value not equal to ‘true’ will result in 0 being returned.
Ways to convert Boolean values to integer 0 1 in Python
Python program to convert given a boolean value into an integer value 0 and 1
Using int() method
x = True
print("Initial value: ", x)
print("Converted value: ", int(x))
Output:
Naive Approach
x = True
if x:
x = 1
else:
x = 0
print(x)
Output: 1
numpy boolean list
import numpy
x = numpy.array([True, False])
x = numpy.multiply(x, 1)
print(x)
Output: [1 0]
Using map() Method
Convert boolean list values into a 0 1.
x = [True, False]
x = list(map(int, x))
print(x)
Output: [1, 0]
Python boolean addition
Since bool is a subclass of int, it can be calculated like integers.
print(True + True)
print(True * 10)
Output:
2
10
Count the number
the list of True
and False
using the built-in function sum()
which calculates the sum of the numbers stored in the list.
print(sum([True, False, True]))
Output: 2
Do comment if you have any doubts and suggestions on this Python true false topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.