Search code examples
pythonlistiteratorboolean

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.

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']