Method: Using itertools.compress()
The most elegant and simple method to accomplish this particular task — use the built-in compress () functionality to filter all elements from a list that exists in True positions relative to the index of another list.
# Python3 demo code work # Filter the list by logical list # Using itertools.compress from itertools import compress # initializing list test_list = [ 6 , 4 , 8 < code class = "plain">, 9 , 10 ] # print list print ( "The original list:" + str (test_list)) # logical list initialization bool_list = [ True , False , False , True , True ] < p> # printing a logical list print ( "The bool list is:" + str (bool_list)) # Filter the list by logical list # Using itertools.compress res = list (compress (test_list , bool_list)) # Print 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]