Boolean list initialization - Python
Last Updated :
29 Jan, 2025
We are given a task to initialize a list of boolean values in Python. A boolean list contains elements that are either True
or False
. Let's explore several ways to initialize a boolean list in Python.
Using List Multiplication
The most efficient way to initialize a boolean list with identical values is by using list multiplication. This approach creates a list with a predefined length and assigns the same boolean value to all elements.
Python
# Initialize a boolean list with 5 elements all set to True
a = [True] * 5
print(a)
Output[True, True, True, True, True]
Explanation:
- This method directly multiplies the boolean value with the desired list size.
- It is ideal when we want to create a list of True or False values in a fixed size.
Let's explore some more ways and see how we can initialize a boolean list in Python.
Using List Comprehension
List comprehension allows us to initialize a boolean list based on a condition. This can be helpful when we need to create a boolean list where each element is determined by some logic.
Python
# Initialize a boolean list of size 5 where the condition is even index -> True
a = [True if i % 2 == 0 else False for i in range(5)]
print(a)
Output[True, False, True, False, True]
Explanation:
- List comprehension allows us to apply conditions dynamically while initializing the list.
- This method works well when the boolean values need to depend on some logic, such as index-based conditions.
Using for Loop
If we need to initialize a boolean list dynamically or based on more complex logic, we can use a for loop.
Python
# Initialize an empty list
a = []
# Append boolean values based on a condition
for i in range(5):
a.append(i % 2 == 0)
print(a)
Output[True, False, True, False, True]
Explanation: This approach manually appends each value to the list based on a condition.
Using map() with Lambda Function
Using map() function with a lambda allows us to apply a function to each element of a sequence, creating the boolean list accordingly.
Python
# Initialize a boolean list based on a lambda function
a = list(map(lambda x: x % 2 == 0, range(5)))
print(a)
Output[True, False, True, False, True]
Explanation: map() function applies a transformation to each item in the sequence, and we use a lambda to define the boolean condition.