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)) |
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 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)) |
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 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)) |
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 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)) |
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. 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 |
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^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)) |
The 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 |
The 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.