Skip to content
Related Articles

Related Articles

Python | Boolean list initialization

View Discussion
Improve Article
Save Article
  • Last Updated : 01 Feb, 2022
View Discussion
Improve Article
Save Article

Many times in programming, we require to initialize a list with some initial values. In Dynamic programming, this is used more often and mostly the requirement is to initialize with a boolean 0 or 1. Let’s discuss certain ways in which this can be achieved.

Method #1: Using list comprehension 
This can easily be done with the naive method, hence, can also be converted into a compact version using list comprehension. This is the most basic way to perform this task.

Python3




# Python3 code to demonstrate
# to perform boolean list initializing
# using list comprehension
 
# using list comprehension
# to perform boolean list initializing
res =  [True for i in range(6)]
 
# printing result
print ("The True initialized list is : " +  str(res))

Output: 

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

 

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

Python3




# Python3 code to demonstrate
# to perform boolean list initializing
# using * operator
 
# using * operator
# to perform boolean list initializing
res =  [True] * 6
 
# printing result
print ("The True initialized list is : " +  str(res))

Output: 

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

 

  
Method #3 : Using bytearray() 
This method can be used to perform the list initialization, but this argument can only be extended to False value initializations. It doesn’t work when we require to initialize with the True values.

Python3




# Python3 code to demonstrate
# to perform boolean list initializing
# using bytearray()
 
# using bytearray()
# to perform boolean list initializing
res = list(bytearray(6))
 
# printing result
print ("The False initialized list is : " +  str(res))

Output: 

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

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!