Python - False indices in a boolean list
Last Updated :
23 Apr, 2023
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 certain ways to get indices of false values in list in Python.
Method #1 : Using enumerate() and list comprehension enumerate() can do the task of hashing index with its value and coupled with list comprehension can let us check for the false values.
Python3
# Python3 code to demonstrate
# False 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
# False indices
res = [i for i, val in enumerate(test_list) if not val]
# printing result
print ("The list indices having False values are : " + str(res))
Output : The original list is : [True, False, True, False, True, True, False]
The list indices having False values are : [1, 3, 6]
Time Complexity: O(n)
Auxiliary Space: O(n), where n is length of list.
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 false values.
Python3
# Python3 code to demonstrate
# False 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()
# False indices
res = list(filter(lambda i: not test_list[i], range(len(test_list))))
# printing result
print ("The list indices having False values are : " + str(res))
Output : The original list is : [True, False, True, False, True, True, False]
The list indices having False values are : [1, 3, 6]
Time Complexity: O(n*n), where n is the length of the input list. This is because we’re using lambda + filter() + range() which has a time complexity of O(n*n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method#3: Using Recursive method.
Algorithm:
- Define a recursive function false_indices that takes an input list test_list and a starting index start.
- Base case: if the starting index is equal to the length of the input list, return an empty list.
- Recursive case: call the false_indices function recursively with the same input list and the starting index incremented by 1, and store the result in a variable called tail.
- If the element at the starting index is False, return a list containing the starting index concatenated with tail.
- If the element at the starting index is True, return tail.
Python3
# Python3 code to demonstrate
# False indices
def false_indices(test_list, start=0):
if start == len(test_list):
return []
tail = false_indices(test_list, start+1)
if not test_list[start]:
return [start] + tail
else:
return tail
# initializing list
test_list = [True, False, True, False, True, True, False]
# printing original list
print ("The original list is : " + str(test_list))
# False indices
res = false_indices(test_list)
# printing result
print ("The list indices having False values are : " + str(res))
OutputThe original list is : [True, False, True, False, True, True, False]
The list indices having False values are : [1, 3, 6]
Time Complexity: O(n)
Auxiliary Space:O(n)
The recursive function false_indices processes each element of the input list exactly once, resulting in a time complexity of O(n), where n is the length of the input list. Since the function is recursive, it will be called n times in the worst case, resulting in a space complexity of O(n), where n is the length of the input list. Each recursive call creates a new stack frame with a constant amount of memory usage, which contributes to the overall space complexity. Therefore, the time complexity of the algorithm is O(n), and the space complexity is also O(n).
METHOD#4:Using a for loop
APPROACH:
This code finds the indices of False values in a boolean list by iterating over the list using a for loop, checking if each value is False using a conditional statement, and adding the index of the False value to a list. The list of indices is then printed.
ALGORITHM
1.Initialize an empty list called false_indices.
2.Loop through the indices of the input list test_list.
3.Check if the element at the current index is False using the not operator.
4.If it is False, append the current index to false_indices.
5.Print the list of indices with False values.
Python3
test_list = [True, False, True, False, True, True, False]
false_indices = []
for i in range(len(test_list)):
if not test_list[i]:
false_indices.append(i)
print("The list indices having False values are :", false_indices)
OutputThe list indices having False values are : [1, 3, 6]
- Time complexity: O(n), where n is the length of the input list.
- Auxiliary Space: O(k), where k is the number of False values in the input list.
METHOD#5: Using reduce():
Algorithm:
- Define a function false_indices which takes a list test_list and an optional integer start (default 0) as input.
- Check if start is equal to the length of the list, if yes, return an empty list.
- Recursively call the false_indices function with an updated start value of start+1 and store the result in the variable tail.
- If the value of test_list[start] is False, return a list consisting of start followed by tail.
Else, return tail.
Python3
from functools import reduce
def false_indices(test_list, start=0):
if start == len(test_list):
return []
tail = reduce(lambda acc, i: acc + [i] if not test_list[i] else acc, range(start+1, len(test_list)), [])
if not test_list[start]:
return [start] + tail
else:
return tail
# initializing list
test_list = [True, False, True, False, True, True, False]
# printing original list
print ("The original list is : " + str(test_list))
# False indices
res = false_indices(test_list)
# printing result
print ("The list indices having False 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 False values are : [1, 3, 6]
Time complexity: O(n), where n is the length of the input list. This is because in the worst case scenario, we need to traverse the entire list to find all the False values.
Space complexity: O(n), where n is the length of the input list. This is because in the worst case scenario, we need to store all the False indices in a list of length n. Additionally, each recursive call to the function also requires some amount of space on the call stack, but this space requirement is negligible compared to the list of False indices.
METHOD 6:Using counter method
APPROACH:
The above program finds the indices of False values in the given boolean list using a list comprehension and the range() function. It also uses the collections.Counter() method to count the number of occurrences of False, although this is not strictly necessary for finding the indices.
ALGORITHM:
1.Import the Counter method from the collections module and define the boolean list to be checked.
2.Use the Counter method to count the number of occurrences of False in the list and store the result in the false_count variable.
3.Use a list comprehension and the range() function to generate a list of indices where the corresponding element in the boolean list is False.
4.Print the list of false indices.
Python3
from collections import Counter
bool_list = [True, False, True, False, True, True, False]
false_count = Counter(bool_list)[False]
false_indices = [i for i in range(len(bool_list)) if not bool_list[i]]
print("The list indices having False values are:", false_indices)
OutputThe list indices having False values are: [1, 3, 6]
The time complexity of this program is O(n)
The space complexity of this program is also O(n)
Similar Reads
Python | Count true booleans in a list
Given a list of booleans, write a Python program to find the count of true booleans in the given list. Examples: Input : [True, False, True, True, False] Output : 3 Input : [False, True, False, True] Output : 2 Method #1: Using List comprehension One simple method to count True booleans in a list i
3 min read
Python | Filter list by Boolean list
Sometimes, while working with a Python list, we can have a problem in which we have to filter a list. This can sometimes, come with variations. One such variation can be filtered by the use of a Boolean list. Let's discuss a way in which this task can be done. Using Numpy to Filter list by Boolean
5 min read
Python - Indices of atmost K elements in list
Many times we might have problem in which we need to find indices rather than the actual numbers and more often, the result is conditioned. First approach coming to mind can be a simple index function and get indices less than or equal than particular number, but this approach fails in case of dupli
7 min read
Python - Duplicate Element Indices in List
We are having a list we need to find the duplicate element indices. For example, we are given a list a = [10, 20, 30, 20, 40, 30, 50] we need to find indices of the duplicate items so that output should be {20: [1, 3], 30: [2, 5]}.Using a loop and a dictionaryWe iterate through the list using enumer
3 min read
Boolean list initialization - Python
We are given a task to initialize a list of boolean values in Python. A boolean list contains elements that are either True or False. Let's explore several ways to initialize a boolean list in Python.Using List MultiplicationThe most efficient way to initialize a boolean list with identical values i
2 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
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 - Common keys in list and dictionary
Given a dictionary and list, extract all the keys and list which are common. Input : test_dict = {"Gfg": 3, "is" : 5, "best" : 9, "for" : 0, "geeks" : 3}, test_list = ["Gfg", "best", "CS"] Output : ['Gfg', 'best'] Explanation : Gfg and best are present in both dictionary and List. Input : test_dict
8 min read
Python - Get Indices of Even Elements from list
Sometimes, while working with Python lists, we can have a problem in which we wish to find Even elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Let us discuss certain ways to find in
8 min read
Python - Odd elements indices
Sometimes, while working with Python lists, we can have a problem in which we wish to find Odd elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Letâs discuss certain way to find indic
7 min read