Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick way to reject a list in Python

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.

like image 341
gt6989b Avatar asked May 30 '13 18:05

gt6989b


People also ask

How do you exclude items from a list in Python?

How do I remove a specific element from a list in Python? The remove() method removes the first matching element (which is passed as an argument) from the list. The pop() method removes an element at a given index, and will also return the removed item.

What is reject in Python?

rejected 3.22. 0 Rejected runs as a master process with multiple consumer configurations that are each run it an isolated process. It has the ability to collect statistical data from the consumer processes and report on it. Rejected supports Python 2.7 and 3.4+.

Is there a list method in Python?

Python has a lot of list methods that allow us to work with lists. In this reference page, you will find all the list methods to work with Python lists. For example, if you want to add a single item to the end of the list, you can use the list. append() method.

How do you restore data in list which is deleted using POP?

You can retrieve the value returned by pop by doing popped=li. pop() where li is the list and the popped value is stored in popped .


1 Answers

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.

like image 84
mgilson Avatar answered Oct 07 '22 17:10

mgilson