- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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]
- Related Articles
- Python Program to get indices of sign change in a list
- Find indices with None values in given list in Python
- Python program to get the indices of each element of one list in another list
- Program to get indices of a list after deleting elements in ascending order in Python
- Get match indices in Python
- Find elements of a list by indices in Python
- Get unique values from a list in Python
- Python – Character indices Mapping in String List
- Python - Ways to find indices of value in list
- Python Group elements at same indices in a multi-list
- Arrange a binary string to get maximum value within a range of indices C/C++?
- Python program to remove elements at Indices in List
- Find the Maximum of Similar Indices in two list of Tuples in Python
- Program to find local peak element indices from a list of numbers in Python
- How to get a list of all the values from a Python dictionary?

Advertisements