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
# 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) |
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
# 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) |
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# 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)) |
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
# 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)) |
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
# Initialising Valuesbool_val = [True, False]# Printing initial Valuesprint("Initial values", bool_val)# Converting boolean to integer using list comprehensionbool_val = [int(b) for b in bool_val]# Printing resultprint("Resultant values", str(bool_val))#This code is contributed by Edula Vinay Kumar Reddy |
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 = Truei = 1 if b else 0print(i) |
1
Time Complexity: O(1)
Auxiliary Space: O(1)


Please Login to comment...