Gather items that cause all() to return false

Question:

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.

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().

Asked By: 0buz

||

Answers:

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']
Answered By: chepner

List comprehension as @chepner mentioned or filter()

>>> list(filter(lambda x:  not isinstance(x, int), lst))
['c', '5']
>>>
Answered By: rasjani
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.