0

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

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
0buz
  • 3,443
  • 2
  • 8
  • 29
  • 2
    Only *one* item can cause `all` to return `False`; `all` stops looking after the first false value. – chepner Feb 10 '23 at 13:04
  • No, `all` doesn't remember the value. `filter` the list instead and check whether it's empty or not, that gives you both infos. – deceze Feb 10 '23 at 13:04
  • 1
    If you wanted that one value, you could use an assignment expression: in `all(isinstance(witness := li, int) for li in lst))`. `witness` remains in scope after `all` is finished with the generator expression. – chepner Feb 10 '23 at 13:06
  • TIL `all` stops on first false value. Makes sense actually. Great tip on using assignment expression too. Thanks @chepner. – 0buz Feb 10 '23 at 13:19
  • "This question is about what one can/cannot do with all() function." - Oh, well, we have a reference duplicate for that, too. – Karl Knechtel Feb 10 '23 at 13:25

2 Answers2

3

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']
chepner
  • 497,756
  • 71
  • 530
  • 681
0

List comprehension as @chepner mentioned or filter()

>>> list(filter(lambda x:  not isinstance(x, int), lst))
['c', '5']
>>>
rasjani
  • 7,372
  • 4
  • 22
  • 35