Python | Boolean list initialization

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.