The Python Oracle

How to do "if-for" statement in python?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Drifting Through My Dreams

--

Chapters
00:00 How To Do &Quot;If-For&Quot; Statement In Python?
00:27 Accepted Answer Score 28
00:48 Answer 2 Score 3
01:05 Answer 3 Score 3
01:17 Answer 4 Score 4
02:02 Thank you

--

Full question
https://stackoverflow.com/questions/4348...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 28


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



ANSWER 2

Score 4


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 



ANSWER 3

Score 3


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.




ANSWER 4

Score 3


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.