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.
Convert Boolean values to integers using int()
Converting bool to an integer using Python typecasting.
Python3
bool_val = True
print ( "Initial value" , bool_val)
bool_val = int (bool_val = = True )
print ( "Resultant value" , bool_val)
|
Output:
Initial value True
Resultant value 1
Time Complexity: O(1)
Auxiliary Space: O(1)
Convert Boolean values to integers using the Naive Approach
Converting bool to an integer using Python loop.
Python3
bool_val = True
print ( "Initial value" , bool_val)
if bool_val:
bool_val = 1
else :
bool_val = 0
print ( "Resultant value" , bool_val)
|
Output:
Initial value True
Resultant value 1
Convert Boolean values to integers using NumPy
In the case where a boolean list is present.
Python3
import numpy
bool_val = numpy.array([ True , False ])
print ( "Initial values" , bool_val)
bool_val = numpy.multiply(bool_val, 1 )
print ( "Resultant values" , str (bool_val))
|
Output:
Initial values [ True False]
Resultant values [1 0]
Convert Boolean values to integers using map()
In a case where a boolean list is present.
Python3
bool_val = [ True , False ]
print ( "Initial value" , bool_val)
bool_val = list ( map ( int , bool_val))
print ( "Resultant value" , str (bool_val))
|
Output:
Initial value [True, False]
Resultant value [1, 0]
Using List comprehension
This approach uses list comprehension to iterate through the list ‘bool_val’ and applies the int() function to each element, which converts the Boolean value to its integer equivalent (1 for True and 0 for False).
Python3
bool_val = [ True , False ]
print ( "Initial values" , bool_val)
bool_val = [ int (b) for b in bool_val]
print ( "Resultant values" , str (bool_val))
|
Output
Initial values [True, False]
Resultant values [1, 0]
Time complexity: O(n)
Space complexity: O(n)
Using the ternary operator to convert boolean to integer:
Approach:
Create a boolean variable b with value True
Use the ternary operator to check if b is True. If it is, assign 1 to the integer variable i, otherwise assign 0.
Print the value of i.
Python3
b = True
i = 1 if b else 0
print (i)
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
28 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...