Python | Ways to convert Boolean values to integer
Given a boolean value(s), write a Python program to convert them into an integer value or list respectively. Given below are a few methods to solve the above task.
Method #1: Using int() method
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Python3
# Python code to demonstrate# to convert boolean value to integer# Initialising Valuesbool_val = True # Printing initial Valuesprint("Initial value", bool_val) # Converting boolean to integerbool_val = int(bool_val == True)# Printing resultprint("Resultant value", bool_val) |
Initial value True Resultant value 1
Method #2: Using Naive Approach
Python3
# Python code to demonstrate# to convert boolean# value to integer# Initialising Valuesbool_val = True # Printing initial Valuesprint("Initial value", bool_val) # Converting boolean to integerif bool_val: bool_val = 1else: bool_val = 0# Printing resultprint("Resultant value", bool_val) |
Initial value True Resultant value 1
Method #3: Using numpy
In case where boolean list is present
Python3
# Python code to demonstrate# to convert boolean# value to integerimport numpy# Initialising Valuesbool_val = numpy.array([True, False]) # Printing initial Valuesprint("Initial values", bool_val) # Converting boolean to integerbool_val = numpy.multiply(bool_val, 1)# Printing resultprint("Resultant values", str(bool_val)) |
Initial values [ True False] Resultant values [1 0]
Method #4: Using map()
in case where boolean list is present
Python3
# Python code to demonstrate# to convert boolean# value to integer# Initialising Valuesbool_val = [True, False] # Printing initial Valuesprint("Initial value", bool_val) # Converting boolean to integerbool_val = list(map(int, bool_val))# Printing resultprint("Resultant value", str(bool_val)) |
Initial value [True, False] Resultant value [1, 0]

