Boolean list initialization in Python

PythonServer Side ProgrammingProgramming

There are scenarios when we need to get a list containing only the Boolean values like true and false. In this article how to create list containing only Boolean values.

With range

We use range function giving it which is the number of values we want. Using a for loop we assign true or false today list as required.

Example

 Live Demo

res = [True for i in range(6)]
# Result
print("The list with binary elements is : \n" ,res)

Output

Running the above code gives us the following result −

The list with binary elements is :
[True, True, True, True, True, True]

With * operator

The * operator can repeat the same value required number of times. We use it to create a list with a Boolean value.

Example

 Live Demo

res = [False] * 6
# Result
print("The list with binary elements is : \n" ,res)

Output

Running the above code gives us the following result −

The list with binary elements is :
[False, False, False, False, False, False]

With bytearray

We can also use the byte array function which will give us 0 as default value.

Example

 Live Demo

res = list(bytearray(5))
# Result
print("The list with binary elements is : \n" ,res)

Output

Running the above code gives us the following result −

The list with binary elements is :
[0, 0, 0, 0, 0]
raja
Published on 09-Jul-2020 16:17:49
Advertisements