Python program to fetch the indices of true values in a Boolean list
Last Updated :
10 May, 2023
Given a list of only boolean values, write a Python program to fetch all the indices with True values from given list. Let's see certain ways to do this task.
Method #1: Using itertools [Pythonic way] itertools.compress() function checks for all the elements in list and returns the list of indices with True values.
Python3
# Python program to fetch the indices
# of true values in a Boolean list
from itertools import compress
# initializing list
bool_list = [False, True, False, True, True, True]
# printing given list
print ("Given list is : " + str(bool_list))
# using itertools.compress()
# to return true indices.
res = list(compress(range(len(bool_list )), bool_list ))
# printing result
print ("Indices having True values are : " + str(res))
Output:Given list is : [False, True, False, True, True, True]
Indices having True values are : [1, 3, 4, 5]
Time complexity: O(n), where n is the number of elements in the boolean list.
Space complexity: O(m), where m is the number of true values in the boolean list.
Method #2: Using enumerate() method enumerate() method hashes the index with its value and coupled with list comprehension can let us check for the true values.
Python3
# Python program to fetch the indices
# of true values in a Boolean list
# initializing list
bool_list = [False, True, False, True, True, True]
# printing given list
print ("Given list is : " + str(bool_list))
# using enumerate() + list comprehension
# to return true indices.
res = [i for i, val in enumerate(bool_list) if val]
# printing result
print ("Indices having True values are : " + str(res))
Output:Given list is : [False, True, False, True, True, True]
Indices having True values are : [1, 3, 4, 5]
Time Complexity : O(n)
Space Complexity : O(n)
Method #3: Using filter() + range()
Python3
# Python program to fetch the indices
# of true values in a Boolean list
# initializing list
bool_list = [False, True, False, True, True, True]
# printing given list
print ("Given list is : " + str(bool_list))
# using lambda + filter() + range()
# to return true indices.
res = list(filter(lambda i: bool_list[i], range(len(bool_list))))
# printing result
print ("Indices having True values are : " + str(res))
Output:Given list is : [False, True, False, True, True, True]
Indices having True values are : [1, 3, 4, 5]
Time Complexity : O(n)
Space Complexity : O(n)
Method#4: Using Recursive method.
Algorithm:
- The function takes a boolean list as input and an optional index parameter (which is initially set to 0).
- It checks the base case, i.e., if the boolean list is empty, it returns an empty list.
- It then checks the first element of the boolean list. If it's True, it appends the current index to the result and recursively
- calls the function with the rest of the list and the index incremented by 1.
- If the first element is False, it simply calls the function recursively with the rest of the list and the index incremented by 1.
- Finally, it returns the list of indices that have True values.
Python3
def true_indices(bool_list, index=0):
if not bool_list: # base case: empty list
return []
if bool_list[0]: # if first element is True
return [index] + true_indices(bool_list[1:], index+1) # append index and recurse on rest of list
else: # if first element is False
return true_indices(bool_list[1:], index+1) # recurse on rest of list
# initializing list
bool_list = [False, True, False, True, True, True]
# printing given list
print("Given list is:", bool_list)
# printing result
print("Indices having True values are:", true_indices(bool_list))
OutputGiven list is: [False, True, False, True, True, True]
Indices having True values are: [1, 3, 4, 5]
Time complexity:
In the worst case, the function needs to examine every element of the boolean list.
For each element, it either appends the index to the result or skips to the next element, so the time complexity is O(N) where N is the length of the boolean list.
Space complexity:
The function uses recursion to process the list and create a list of indices that have True values.
In the worst case, when all elements of the boolean list are True, the function creates a list of size N, where N is the length of the boolean list.
Therefore, the space complexity is O(N) where N is the length of the boolean list.
Numpy approach to fetch the indices of True values in a boolean list:
Algorithm:
Convert the boolean list to a numpy array.
Use np.where() function to get the indices of True values.
Convert the resulting tuple to a list.
Python3
import numpy as np
# initializing list
bool_list = [False, True, False, True, True, True]
# printing given list
print("Given list is:", bool_list)
# converting to numpy array
bool_arr = np.array(bool_list)
# getting indices of True values
res = list(np.where(bool_arr)[0])
# printing result
print("Indices having True values are:", res)
Output:
Given list is: [False, True, False, True, True, True]
Indices having True values are: [1, 3, 4, 5]
Time complexity: O(n), where n is the number of elements in the boolean list.
Space complexity: O(n), where n is the number of elements in the boolean list.
Similar Reads
Python | Get indices of True values in a binary list
Boolean lists are often used by developers to check for True values during hashing. The boolean list is also used in certain dynamic programming paradigms in dynamic programming. Let's discuss certain ways to get indices of true values in a list in Python. Method #1 : Using enumerate() and list comp
9 min read
Python Program to find tuple indices from other tuple list
Given Tuples list and search list consisting of tuples to search, our task is to write a Python Program to extract indices of matching tuples. Input : test_list = [(4, 5), (7, 6), (1, 0), (3, 4)], search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]Output : [3, 1]Explanation : (3, 4) from search list is fo
8 min read
Python program to unique keys count for Value in Tuple List
Given dual tuples, get a count of unique keys for each value present in the tuple. Input : test_list = [(3, 4), (1, 2), (2, 4), (8, 2), (7, 2), (8, 1), (9, 1), (8, 4), (10, 4)] Output : {4: 4, 2: 3, 1: 2} Explanation : 3, 2, 8 and 10 are keys for value 4. Input : test_list = [(3, 4), (1, 2), (8, 1),
6 min read
Python program to extract the Unique Dictionary Value List elements
Given Dictionary with value lists, extract all unique values. Input : test_dict = {"Gfg" : [6, 7, 4, 6], "Geeks" : [6, 8, 5, 2]} Output : [6, 7, 4, 8, 5, 2] Explanation : All distincts elements extracted. Input : test_dict = {"Gfg" : [6, 7, 6], "Geeks" : [6, 8, 5, 2]} Output : [6, 7, 8, 5, 2] Explan
6 min read
Python - False indices in a boolean list
Boolean lists are often used by the developers to check for False values during hashing. These have many applications in developers daily life. Boolean list is also used in certain dynamic programming paradigms in dynamic programming. Also in Machine Learning preprocessing of values. Lets discuss ce
7 min read
Python - Ways to find indices of value in list
In Python, it is common to locate the index of a particular value in a list. The built-in index() method can find the first occurrence of a value. However, there are scenarios where multiple occurrences of the value exist and we need to retrieve all the indices. Python offers various methods to achi
3 min read
Python program to check whether the values of a dictionary are in same order as in a list
Given a dictionary, test if values are in order with list values. Input : test_dict = {"gfg" : 4, "is" : 10, "best" : 11}, sub_list = [4, 10, 11] Output : True Explanation : Values are 4, 10, 11, same as list order. Hence True is returned. Input : test_dict = {"gfg" : 4, "is" : 10, "best" : 11}, sub
6 min read
Python - Start and End Indices of words from list in String
Given a String, our task is to write a Python program to extract the start and end index of all the elements of words of another list from a string. Input : test_str = "gfg is best for all CS geeks and engineering job seekers", check_list = ["geeks", "engineering", "best", "gfg"]Output : {'geeks': [
7 min read
Python Program to display keys with same values in a dictionary List
Given a list with all dictionary elements, the task is to write a Python program to extract keys having similar values across all dictionaries. Examples: Input : test_list = [{"Gfg": 5, "is" : 8, "best" : 0}, {"Gfg": 5, "is" : 1, "best" : 0}, {"Gfg": 5, "is" : 0, "best" : 0}] Output : ['Gfg', 'best'
5 min read
Python program to Test if all y occur after x in List
Given a List, test if all occurrences of y are after the occurrence of x in the list. Input : test_list = [4, 5, 6, 2, 4, 5, 2, 9], x, y = 6, 2 Output : True Explanation : All occurrences of 2 are after 6, hence true. Input : test_list = [4, 2, 5, 6, 2, 4, 5, 2, 9], x, y = 6, 2 Output : False Explan
4 min read