Python | Get indices of True values in a binary list
Last Updated :
12 Apr, 2023
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 comprehension enumerate() can do the task of hashing index with its value and couple with list comprehension can let us check for the true values.
Python3
# Python3 code to demonstrate
# to return true value indices.
# using enumerate() + list comprehension
# initializing list
test_list = [True, False, True, False, True, True, False]
# printing original list
print("The original list is : " + str(test_list))
# using enumerate() + list comprehension
# to return true indices.
res = [i for i, val in enumerate(test_list) if val]
# printing result
print("The list indices having True values are : " + str(res))
OutputThe original list is : [True, False, True, False, True, True, False]
The list indices having True values are : [0, 2, 4, 5]
Time Complexity: O(n) where n is the length of the list as the code iterates through the entire list using a for loop.
Auxiliary Space: O(1) as no additional data structure is used, only a variable to store the result is used.
Method #2 : Using lambda + filter() + range() filter() function coupled with lambda can perform this task with help of range function. range() function is used to traverse the entire list and filter checks for true values.
Python3
# Python3 code to demonstrate
# to return true value indices.
# using lambda + filter() + range()
# initializing list
test_list = [True, False, True, False, True, True, False]
# printing original list
print("The original list is : " + str(test_list))
# using lambda + filter() + range()
# to return true indices.
res = list(filter(lambda i: test_list[i], range(len(test_list))))
# printing result
print("The list indices having True values are : " + str(res))
OutputThe original list is : [True, False, True, False, True, True, False]
The list indices having True values are : [0, 2, 4, 5]
Time complexity: O(n) where n is the length of the list.
Auxiliary space: O(1), as the memory used is constant and does not depend on the size of the list.
Method #3 : Using itertools.compress() compress function checks for all the elements in list and returns the list of indices with True values. This is most Pythonic and elegant way to perform this particular task.
Python3
# Python3 code to demonstrate
# to return true value indices.
# using itertools.compress()
from itertools import compress
# initializing list
test_list = [True, False, True, False, True, True, False]
# printing original list
print("The original list is : " + str(test_list))
# using itertools.compress()
# to return true indices.
res = list(compress(range(len(test_list)), test_list))
# printing result
print("The list indices having True values are : " + str(res))
OutputThe original list is : [True, False, True, False, True, True, False]
The list indices having True values are : [0, 2, 4, 5]
Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(m), where m is the number of True values in the input list test_list.
Method #4 : Using for loop
Python3
# Python3 code to demonstrate
# to return true value indices.
# initializing list
test_list = [True, False, True, False, True, True, False]
# printing original list
print("The original list is : " + str(test_list))
res = []
for i in range(len(test_list)):
if test_list[i]:
res.append(i)
# printing result
print("The list indices having True values are : " + str(res))
OutputThe original list is : [True, False, True, False, True, True, False]
The list indices having True values are : [0, 2, 4, 5]
Time complexity: O(n), where n is the length of the input list. The code iterates through the list once to identify the indices of the True values.
Auxiliary space complexity: O(m), where m is the number of True values in the input list. This is because the code creates a new list to store the indices of the True values. The space required is proportional to the number of True values, not the size of the input list.
Method #5: Using list.index()
You can use the list.index() method to find the index of the first occurrence of a True value in the list. Then, you can use a loop to find the indices of all subsequent True values by calling list.index() again on the sublist starting from the next index.
Here is an example of how to use this method:
Python3
# Python3 code to demonstrate
# to return true value indices.
# using list.index()
# initializing list
test_list = [True, False, True, False, True, True, False]
# printing original list
print("The original list is : " + str(test_list))
# using list.index()
# to return true indices.
res = []
i = 0
while True:
try:
i = test_list.index(True, i)
res.append(i)
i += 1
except ValueError:
break
# printing result
print("The list indices having True values are : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original list is : [True, False, True, False, True, True, False]
The list indices having True values are : [0, 2, 4, 5]
Time complexity: O(N^2)
Auxiliary space: O(N)
Method#6:Using Recursive method.
Algorithm:
- Start with an index of 0.
- If the index is equal to or greater than the length of the list, return an empty list.
- If the element at the current index is True, add the index to the result and recursively call the function with the next index.
- If the element at the current index is False, simply recursively call the function with the next index.
- Return the result.
Python3
def find_true_indices(lst, index=0):
if index >= len(lst):
return []
elif lst[index]:
return [index] + find_true_indices(lst, index+1)
else:
return find_true_indices(lst, index+1)
# initializing list
test_list = [True, False, True, False, True, True, False]
# printing original list
print("The original list is : " + str(test_list))
true_indices = find_true_indices(test_list)
# printing result
print("The list indices having True values are : " + str(true_indices))
OutputThe original list is : [True, False, True, False, True, True, False]
The list indices having True values are : [0, 2, 4, 5]
Time Complexity:
In the worst case, where all elements in the list are False, the function will be called n times (where n is the length of the list) before reaching the base case, resulting in O(n) time complexity.
In the best case, where the first element in the list is True, the function will only be called once, resulting in O(1) time complexity.
On average, assuming a uniform distribution of True and False values in the list, the function will be called approximately n/2 times before reaching the base case, resulting in O(n) time complexity.
Space Complexity:
The space complexity of the function is proportional to the depth of the recursion, which is equal to the number of True values in the list.
In the worst case, where all elements in the list are True, the space complexity will be O(n).
In the best case, where all elements in the list are False, the space complexity will be O(1).
On average, assuming a uniform distribution of True and False values in the list, the space complexity will be O(n/2), which simplifies to O(n) in big O notation.
Method #7: Using NumPy's nonzero() function
NumPy's nonzero() function returns the indices of the elements that are non-zero. This function can be used to find the indices of the True values in the list.
Step-by-step approach:
- Import the NumPy library.
- Initialize the list with the input values.
- Print the original list to show the input.
- Use the np.nonzero() function to find the indices of non-zero (True) values in the input list.
- Store the result in a variable.
- Print the result to show the indices of True values in the list.
Below is the implementation of the above approach:
Python3
import numpy as np
# initializing list
test_list = [True, False, True, False, True, True, False]
# printing original list
print("The original list is : " + str(test_list))
# using NumPy's nonzero() function
# to return true indices.
res = np.nonzero(test_list)[0]
# printing result
print("The list indices having True values are : " + str(res))
Output:
The original list is : [True, False, True, False, True, True, False]
The list indices having True values are : [0 2 4 5]
Time Complexity: O(n), where n is the length of the input list.
Auxiliary Space: O(n), where n is the length of the input list, as NumPy creates a new array to store the indices.
Method #8: Using heapq:
Algorithm:
- Create a list comprehension that iterates over each index-value pair in the input list using enumerate().
- Check if the value of the current pair is True.
- If it is, append the index to the output list res.
- Return the output list.
Python3
import heapq
test_list = [True, False, True, False, True, True, False]
# printing original list
print("The original list is : " + str(test_list))
res = [i for i in heapq.nlargest(test_list.count(True), range(len(test_list)), key=lambda i: test_list[i])]
print("The list indices having True values are : " + str(res))
#This code is contributed by Rayudu
OutputThe original list is : [True, False, True, False, True, True, False]
The list indices having True values are : [0, 2, 4, 5]
Time complexity:
The time complexity of this code is O(n), where n is the length of the input list. This is because the list comprehension iterates over each index-value pair in the list once, which takes O(n) time. The if statement inside the list comprehension takes O(1) time.
Auxiliary Space:
The space complexity of this code is O(n), where n is the length of the input list. This is because the output list res can potentially contain all n indices of the input list, and therefore takes O(n) space. The list comprehension itself takes O(1) space, since it only stores the current index-value pair.
Similar Reads
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 fetch the indices of true values in a Boolean list
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 w
5 min read
Get Index of Values in Python Dictionary
Dictionary values are lists and we might need to determine the position (or index) of each element within those lists. Since dictionaries themselves are unordered (prior to Python 3.7) or ordered based on insertion order (in Python 3.7+), the concept of "index" applies to the valuesâspecifically whe
3 min read
Python | Find indices with None values in given list
Many times while working in data science domain we need to get the list of all the indices which are None, so that they can be easily be prepossessed. This is quite a popular problem and solution to it comes quite handy. Let's discuss certain ways in which this can be done. Method #1 : Using list co
7 min read
Python | Get first index values in tuple of strings
Yet another peculiar problem which might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This articles solves problem of extracting only the fi
5 min read
Python - Test Kth index in Dictionary value list
Sometimes, while working with Python dictionaries, we can have a problem in which we need to test if, throughout the dictionary, the kth index of all values in the dictionary is equal to N. This kind of problem can occur in the web development domain. Let's discuss certain ways in which this problem
9 min read
Python - Truth values deletion in List
Due to the upcoming of Machine Learning, focus has now moved on handling the values than ever before, the reason behind this is that it is the essential step of data preprocessing before it is fed into further techniques to perform. Hence removal of values in essential, be it None, or sometimes Trut
5 min read
Counting number of unique values in a Python list
Counting the number of unique values in a Python list involves determining how many distinct elements are present disregarding duplicates.Using a SetUsing a set to count the number of unique values in a Python list leverages the property of sets where each element is stored only once.Pythonli = [1,
2 min read
Python - Convert List to Index and Value dictionary
Given a List, convert it to dictionary, with separate keys for index and values. Input : test_list = [3, 5, 7, 8, 2, 4, 9], idx, val = "1", "2" Output : {'1': [0, 1, 2, 3, 4, 5, 6], '2': [3, 5, 7, 8, 2, 4, 9]} Explanation : Index and values mapped at similar index in diff. keys., as "1" and "2". Inp
4 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