Python | Boolean list initialization

Python Methods and Functions

Method # 1: Using List Comprehension
This can be easily done with a naive method, hence it can also be converted to a compact version using a list comprehension. This is the easiest way to accomplish this task.

# Python3 demo code
# initialize boolean list
# using comprehension list

 
# use comprehension list
# initialize the boolean list

res =   [ True for i in range ( 6 )]

  
# print result ati

print ( "The True initialized list is: " +   str (res))

Exit:

 The True initialized list is: [ True, True, True, True, True, True] 

Method # 2: Using the * operator
This can be done using the * in a relatively more readable and compact way. Let`s multiply a single list N no. times to get the desired result.

# Python3 demo code
# initialize the boolean list
# using the * operator

 
# using the * operator
# initialize the boolean list

res =   [ True ] * 6

  
# print result

print ( "The True initialized list is:" +   str (res))

Exit :

 The True initialized list is: [True, True, True, True, True, True] 

Method # 3: Using bytearray()
This method can be used to initialize a list, but this argument can only be extended on initialization false values. This doesn`t work when we need to initialize to True.

# Python3 demo code
# initialize the boolean list
# using bytearray ()

  
# using bytearray ()
# initialize the boolean list

res = list (bytearray ( 6 ))

  
# print result

print ( "The False initialized list is: " +   str (res))

Exit:

 The False initialized list is: [0, 0 , 0, 0, 0, 0] 




Get Solution for free from DataCamp guru