A quick way to reject a list in Python

I have a list of elements in python and a way to check if an element is valid. I need to reject the entire list if any of the elements there are invalid. I could do this:

def valid(myList): for x in myList: if isInvalid(x): return False return True 

Is there a more pythonic way to do this? You can filter it, but it will evaluate all the items in the list if only the first rating can be sufficient (if it's bad) ...

Many thanks for your help.

+6
source share
1 answer

A typical way to do this is to use the any built-in function with a generator expression

 if any(isInvalid(x) for x in myList): #reject 

The syntax is clean and elegant, and you get the same short circuit that you had on the original function.

+14
source

Source: https://habr.com/ru/post/946205/


All Articles