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
Selected Reading
Get indices of True values in a binary list in Python
When a Python list contains values like true or false and 0 or 1 it is called binary list. In this article we will take a binary list and find out the index of the positions where the list element is true.
With enumerate
The enumerate function extracts all the elements form the list. We apply a in condition to check of the extracted value is true or not.
Example
listA = [True, False, 1, False, 0, True]
# printing original list
print("The original list is :\n ",listA)
# using enumerate()
res = [i for i, val in enumerate(listA) if val]
# printing result
print("The indices having True values:\n ",res)
Output
Running the above code gives us the following result −
The original list is : [True, False, 1, False, 0, True] The indices having True values: [0, 2, 5]
With compress
Using compress we iterate through each of the element in the list. This brings out only the elements whose value is true.
Example
from itertools import compress
listA = [True, False, 1, False, 0, True]
# printing original list
print("The original list is :\n ",listA)
# using compress()
res = list(compress(range(len(listA)), listA))
# printing result
print("The indices having True values:\n ",res)
Output
Running the above code gives us the following result −
The original list is : [True, False, 1, False, 0, True] The indices having True values: [0, 2, 5]
Advertisements
