Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most 'pythonic' way to logically combine a list of booleans?

I have a list of booleans I'd like to logically combine using and/or. The expanded operations would be:

vals = [True, False, True, True, True, False]  # And-ing them together result = True for item in vals:     result = result and item  # Or-ing them together result = False for item in vals:     result = result or item 

Are there nifty one-liners for each of the above?

like image 234
BobC Avatar asked Sep 09 '10 02:09

BobC


People also ask

How do you combine Booleans in Python?

We combine Boolean values using four main logical operators (or logical connectives): not, and, or, and ==. All decisions that can be made by Python—or any computer language, for that matter—can be made using these logical operators.

How do you combine Boolean arrays?

const arr = [[true,false,false],[false,false,false],[false,false,true]]; We are required to write a function that merges this array of arrays into a one-dimensional array by combining the corresponding elements of each subarray using the AND (&&) operator.

How do you make a Boolean list of values?

With * operator The * operator can repeat the same value required number of times. We use it to create a list with a Boolean value.

Can you have a list of booleans?

A boolean list ("blist") is a list that has no holes and contains only true and false . Boolean lists can be represented in an efficient compact form, see 22.5 for details. Boolean lists are lists and all operations for lists are therefore applicable to boolean lists.


2 Answers

See all(iterable) :

Return True if all elements of the iterable are true (or if the iterable is empty).

And any(iterable) :

Return True if any element of the iterable is true. If the iterable is empty, return False.

like image 171
NullUserException Avatar answered Sep 17 '22 14:09

NullUserException


The best way to do it is with the any() and all() functions.

vals = [True, False, True, True, True] if any(vals):    print "any() reckons there's something true in the list." if all(vals):    print "all() reckons there's no non-True values in the list." if any(x % 4 for x in range(100)):    print "One of the numbers between 0 and 99 is divisible by 4." 
like image 32
Jerub Avatar answered Sep 20 '22 14:09

Jerub