Open In App

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 list 

Here, we will use np.array to filter out the list with a value True.






import numpy as np
 
lis = np.array([1, 2, 3, 4])
filter = np.array([True, False, True, False])
lis[filter]

Output :

array([1, 3])

Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. numpy performs n number of operations.
Auxiliary Space: O(1), constant extra space is required 



Using itertools.compress()  to Filter list by Boolean list

The most elegant and straightforward method to perform this particular task is to use the inbuilt functionality of compress() to filter out all the elements from a list that exists at Truth positions with respect to the index of another list. 




from itertools import compress
 
# initializing list
test_list = [6, 4, 8, 9, 10]
 
# printing list
print("The original list : " + str(test_list))
 
# initializing Boolean list
bool_list = [True, False, False, True, True]
 
# printing boolean list
print("The bool list is : " + str(bool_list))
 
# Filter list by Boolean list
# Using itertools.compress
res = list(compress(test_list, bool_list))
 
# Printing result
print("List after filtering is : " + str(res))

Output :

 
The original list : [6, 4, 8, 9, 10]
The bool list is : [True, False, False, True, True]
List after filtering is : [6, 9, 10]

Using list comprehension to Filter list by Boolean list 

Here, we will use list comprehension to Filter lists by Boolean using the if condition.




import numpy as np
 
lis = np.array([1, 2, 3, 4])
filter_lis = np.array([True, False, True, False])
filtered_list = [lis[i] for i in range(len(lis)) if filter_lis[i]]
filtered_list

Output :

[1, 3]

Approach:




my_list = [1, 2, 3, 4, 5]
bool_list = [True, False, True, False, True]
 
filtered_list = [x for x, flag in zip(my_list, bool_list) if flag]
 
print(filtered_list)  # Output: [1, 3, 5]

Output
[1, 3, 5]

The time complexity of this code is O(n), where n is the length of the input lists my_list and bool_list. This is because the code loops through the lists once to create the filtered_list. The time complexity is dominated by the zip() function and the list comprehension.

The auxiliary space of this code is O(k), where k is the length of the filtered_list. This is because the filtered_list is the only additional data structure created, and its size depends on the number of True values in bool_list. 

Using a for loop:




list1 = [1, 2, 3, 4, 5]
bool_list = [True, False, True, False, True]
new_list = []
for i in range(len(list1)):
    if bool_list[i]:
        new_list.append(list1[i])
print(new_list) # Output: [1, 3, 5]

Output
[1, 3, 5]

Time complexity: O(n)
Space complexity: O(n)

Using pandas

In this method we first initializes a list named test_list and a boolean list named bool_list. It then creates a pandas series from the original list using pd.Series() function and filters the series using boolean indexing with bool_list. The resulting filtered series is then converted back to a list using the tolist() function, and the final filtered list is printed using the print() function.




import pandas as pd
 
# initializing list
test_list = [1, 2, 3, 4]
 
# printing list
print("The original list : " + str(test_list))
 
# initializing Boolean list
bool_list = [True, False, True, False]
 
# printing boolean list
print("The bool list is : " + str(bool_list))
 
# create a pandas series from the original list
series = pd.Series(test_list)
 
# filter the series by the boolean list
filtered_series = series[bool_list]
 
# convert the filtered series back to a list
res = filtered_series.tolist()
 
# Printing result
print("List after filtering is : " + str(res))

Output:

The original list : [1, 2, 3, 4]
The bool list is : [True, False, True, False]
List after filtering is : [1, 3]

Time complexity: O(n), where n is the length of the original list
Auxiliary Space: O(n), where n is the length of the original list


Article Tags :