Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Gather items that cause all() to return false

This question is about what one can/cannot do with all() function.

I would like to identify all elements which fail the condition set in all() function.

In the example below all() will return False since not all elements are of type int. 'c' and '5' will fail the condition.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

lst=[1,2,'c',4,'5']
all(isinstance(li,int) for li in lst)
>>>False

I could parse the list myself in an equivalent function and build up a list with failing elements, but I wonder if there is a cleverer way of getting ['c','5'] while still using all().

>Solution :

You can’t use all for this, because all stops iterating once it finds a false value. You should use a list comprehension instead.

>>> [li for li in qst if not isinstance(li, int)]
['c', '5']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading