Reputation: 145
With python, I would like to run a test over an entire list, and, if all the statements are true for each item in the list, take a certain action.
Pseudo-code: If "test involving x" is true for every x in "list", then do "this".
It seems like there should be a simple way to do this.
What syntax should I use in python?
Upvotes: 13
Views: 10896
Reputation: 23
all()
alone doesn't work well if you need an extra map()
phase.
see below:
all((x==0 for x in xrange(1000))
and:
all([x==0 for x in xrange(1000)])
the 2nd example will perform 1000 compare even the 2nd compare render the whole result false.
Upvotes: 0
Reputation: 17741
Example (test all elements are greater than 0)
if all(x > 0 for x in list_of_xs):
do_something()
Above originally used a list comprehension (if all([x > 0 for x in list_of_xs]):
) which as pointed out by delnan (Thanks) a generator expression would be faster as the generator expression terminates at the first False
, while this expression applies the comparison to all elements of the list.
However, be careful with generator expression like:
all(x > 0 for x in list_of_xs)
If you are using pylab (launch ipython as 'ipython -pylab'), the all function is replaced with numpy.all which doesn't process generator expressions properly.
all([x>0 for x in [3,-1,5]]) ## False
numpy.all([x>0 for x in [3,-1,5]]) ## False
all(x>0 for x in [3,-1,5]) ## False
numpy.all(x>0 for x in [3,-1,5]) ## True
Upvotes: 4
Reputation: 601789
Use all()
. It takes an iterable as an argument and return True
if all entries evaluate to True
. Example:
if all((3, True, "abc")):
print "Yes!"
You will probably need some kind of generator expression, like
if all(x > 3 for x in lst):
do_stuff()
Upvotes: 28
Reputation: 28693
if reduce(lambda x, y: x and involve(y), yourlist, True):
certain_action()
involve
is the action you want to involve for each element in the list, yourlist
is your original list, certain_action
is the action you want to perform if all the statements are true.
Upvotes: 3
Reputation: 131687
>>> x = [True, False, True, False]
>>> all(x)
False
all() returns True
if all the elements in the list are True
Similarly, any() will return True
if any element is true.
Upvotes: 6
Reputation: 38798
I believe you want the all()
method:
$ python
>>> help(all)
Help on built-in function all in module __builtin__:
all(...)
all(iterable) -> bool
Return True if bool(x) is True for all values x in the iterable.
Upvotes: 3