Skip to content
Related Articles

Related Articles

Python | Ways to convert Boolean values to integer
  • Last Updated : 30 Jun, 2019

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




# Python code to demonstrate 
# to convert boolean value to integer
  
# Initialsing Values
bool_val = True
   
# Printing initial Values
print("Initial value", bool_val)
   
# Converting boolean to integer
bool_val = int(bool_val == True)
  
# Printing result
print("Resultant value", bool_val)
         
Output:
Initial value True
Resultant value 1

 
Method #2: Using Naive Approach




# Python code to demonstrate 
# to convert boolean
# value to integer
  
# Initialsing Values
bool_val = True
   
# Printing initial Values
print("Initial value", bool_val)
   
# Converting boolean to integer
if bool_val:
    bool_val = 1
else:
    bool_val = 0
# Printing result
print("Resultant value", bool_val)
         
Output:



Initial value True
Resultant value 1

 
Method #3: Using numpy
In case where boolean list is present




# Python code to demonstrate 
# to convert boolean
# value to integer
  
import numpy
# Initialsing Values
bool_val = numpy.array([True, False])
   
# Printing initial Values
print("Initial values", bool_val)
   
# Converting boolean to integer
bool_val = numpy.multiply(bool_val, 1)
# Printing result
print("Resultant values", str(bool_val))
Output:
Initial values [ True False]
Resultant values [1 0]

 
Method #4: Using map()
in case where boolean list is presen




# Python code to demonstrate 
# to convert boolean
# value to integer
  
# Initialsing Values
bool_val = [True, False]
   
# Printing initial Values
print("Initial value", bool_val)
   
# Converting boolean to integer
bool_val = list(map(int, bool_val))
  
# Printing result
print("Resultant value", str(bool_val))
Output:
Initial value [True, False]
Resultant value [1, 0]

 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

My Personal Notes arrow_drop_up
Recommended Articles
Page :