Skip to content
Related Articles

Related Articles

Improve Article
Python | Boolean list initialization
  • Last Updated : 04 Jan, 2019

Many a 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 naive method, hence, can also be converted in compact version using list comprehension. This is the most basic way to perform this task.




# 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 * operator with comparatively more readable and compact way. We multiply the single list N no. of times to get the desired result.




# 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 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]

 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 :