Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Boolean list initialization in Python
There are scenarios when we need to create a list containing only Boolean values like True and False. Python provides several methods to initialize Boolean lists efficiently.
Using List Comprehension with range()
We can use list comprehension with range() to create a list of Boolean values. This approach gives us flexibility to set different values based on conditions ?
# Create a list of True values
bool_list = [True for i in range(6)]
print("The list with Boolean elements is:", bool_list)
# Create alternating True/False pattern
alternating = [i % 2 == 0 for i in range(6)]
print("Alternating Boolean list:", alternating)
The list with Boolean elements is: [True, True, True, True, True, True] Alternating Boolean list: [True, False, True, False, True, False]
Using the * (Multiplication) Operator
The multiplication operator can repeat the same Boolean value a specified number of times. This is the most concise method for uniform Boolean lists ?
# Create list of False values
false_list = [False] * 6
print("List of False values:", false_list)
# Create list of True values
true_list = [True] * 4
print("List of True values:", true_list)
List of False values: [False, False, False, False, False, False] List of True values: [True, True, True, True]
Using bytearray() for Binary-like Lists
The bytearray() function creates a list of zeros, which can represent False in Boolean context. Note that this creates integers, not actual Boolean values ?
# Create list of zeros (falsy values)
zero_list = list(bytearray(5))
print("List with zero elements:", zero_list)
# Convert to actual Boolean values
bool_from_zeros = [bool(x) for x in zero_list]
print("Converted to Boolean:", bool_from_zeros)
List with zero elements: [0, 0, 0, 0, 0] Converted to Boolean: [False, False, False, False, False]
Using itertools.repeat()
For larger lists, itertools.repeat() provides memory-efficient initialization ?
import itertools
# Create Boolean list using itertools
bool_list = list(itertools.repeat(True, 5))
print("Using itertools.repeat():", bool_list)
Using itertools.repeat(): [True, True, True, True, True]
Comparison
| Method | Best For | Flexibility | Performance |
|---|---|---|---|
[True] * n |
Uniform values | Low | Fastest |
| List comprehension | Conditional logic | High | Good |
itertools.repeat() |
Large lists | Medium | Memory efficient |
bytearray() |
Binary-like data | Low | Good |
Conclusion
Use [value] * n for simple uniform Boolean lists. Use list comprehension when you need conditional logic or patterns. For memory efficiency with large lists, consider itertools.repeat().
