Check immediately boolean values ​​from a set of variables

I have about 10 boolean variables, I need to set a new boolean variable x=True , if all these ten variable values ​​are True. If one of them is False, then set x= False , I can do it in a way

 if (a and b and c and d and e and f...): x = True else: x=False 

which clearly looks very ugly. Please suggest some more python solutions.

The ugly part of a and b and c and d and e and f...

+4
source share
4 answers

Assuming you have bools in a list / tuple:

 x = all(list_of_bools) 

or just as suggested by @minopret

 x= all((a, b, c, d, e, f)) 

Example:

 >>> list_of_bools = [True, True, True, False] >>> all(list_of_bools) False >>> list_of_bools = [True, True, True, True] >>> all(list_of_bools) True 
+9
source

Although using all is one and preferably only obvious way to do it in Python, here is another way to do the same with the and_ function from operator and reduce

 >>> a = [True, True, False] >>> from operator import and_ >>> reduce(and_, a) False >>> b = [True, True, True] >>> reduce(and_, b) True 

Edit: As mentioned by Duncan, and_ is the bitwise operator of & , not the logical and . It will only work for boolean values, since they will be passed to int (1 or 0)

Following the comments, you really need to use BIF all to achieve what the OP asked. I wanted to add this as an answer because I find it useful sometimes, for example, for creating complex db queries in Django using Q objects and in some other cases.

+1
source
 is_all_true = lambda *args:all(args) a = True b = True c = True print is_all_true(a,b,c) 
+1
source
 x = a and b and c and d and e ... 

If this is something that would need to be calculated many times, consider using a function that receives all the logical values ​​(preferably a list or tuple, without assuming anything about its size).

0
source

All Articles