Open In App

Python | Filter list by Boolean list

Last Updated : 16 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Python3




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. 

Python3




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.

Python3




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:

  • Define a list my_list containing the values to filter.
  • Define a list bool_list containing the boolean values to filter the list by.
  • Use a list comprehension to iterate over both lists simultaneously using the zip() function.
  • Check if the current element of my_list should be included in the filtered list by checking the corresponding boolean value in bool_list.
  • If the boolean value is True, include the current element in the filtered list using the append() method or a list comprehension with an if condition.
  • Print the filtered list.

Python3




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:

  • Initialize a list variable list1 with some integer values, and a Boolean list variable bool_list with some Boolean values.
  • Initialize an empty list variable new_list.
  • Use a for loop to iterate through each index i in the range of length of the list1.
  • Inside the loop, check if the value of the Boolean list bool_list at the current index i is True using the condition if bool_list[i]:.
  • If the condition is true, append the value of the list1 at the current index i to the new_list variable using the append() function.
  • After the loop, the new_list variable will contain only the elements of list1 whose corresponding value in bool_list is True.
  • Finally, you can use the print() function to display the new list new_list.

Python3




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.

Python3




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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads