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
Get indices of True values in a binary list in Python
When a Python list contains boolean values like True or False and numeric values like 1 or 0, it is called a binary list. In this article, we will take a binary list and find the indices of positions where the list element evaluates to True.
Using enumerate() with List Comprehension
The enumerate() function extracts all elements from the list along with their indices. We apply a condition to check if the extracted value is truthy or not ?
Example
binary_list = [True, False, 1, False, 0, True]
# printing original list
print("The original list is:\n", binary_list)
# using enumerate() with list comprehension
result = [i for i, val in enumerate(binary_list) if val]
# printing result
print("The indices having True values:\n", result)
The output of the above code is ?
The original list is: [True, False, 1, False, 0, True] The indices having True values: [0, 2, 5]
Using itertools.compress()
Using compress(), we iterate through each element in the list. This function filters indices based on corresponding truthy values in the binary list ?
Example
from itertools import compress
binary_list = [True, False, 1, False, 0, True]
# printing original list
print("The original list is:\n", binary_list)
# using compress() to get indices
result = list(compress(range(len(binary_list)), binary_list))
# printing result
print("The indices having True values:\n", result)
The output of the above code is ?
The original list is: [True, False, 1, False, 0, True] The indices having True values: [0, 2, 5]
Using numpy.where()
For larger datasets, NumPy provides an efficient where() function that returns indices of elements satisfying a condition ?
Example
import numpy as np
binary_list = [True, False, 1, False, 0, True]
binary_array = np.array(binary_list)
# printing original list
print("The original list is:\n", binary_list)
# using numpy.where()
result = np.where(binary_array)[0].tolist()
# printing result
print("The indices having True values:\n", result)
The output of the above code is ?
The original list is: [True, False, 1, False, 0, True] The indices having True values: [0, 2, 5]
Comparison
| Method | Memory Usage | Performance | Best For |
|---|---|---|---|
enumerate() |
Low | Good | Small to medium lists |
compress() |
Low | Good | Functional programming style |
numpy.where() |
Higher | Excellent | Large datasets |
Conclusion
Use enumerate() with list comprehension for simple cases and readability. For large datasets, numpy.where() provides better performance. The compress() method offers a functional programming approach for filtering indices.
