Question

I have a list of items in python, and a way to check if the item is valid or not. I need to reject the entire list if any one of items there is 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 for doing this? You could filter it, but that would evaluate all the items in the list, when evaluating just the first one could be sufficient (if it is bad)...

Thank you very much for your help.

Was it helpful?

Solution

The typical way to do this is to use the builtin any 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-circuiting behavior that you had on your original function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top