Change language

Python | Filter list by logical list

| |

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] 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method