views:

102

answers:

2

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?

+14  A: 

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.

NullUserException
Yep, exactly the right response, +1!
Alex Martelli
Many thanks! I googled like crazy before asking, and found nothing.
BobC
+4  A: 

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."
Jerub
My boolean list is generated by a list comprehension on another list. Now I can wrap them all together. Nice!
BobC
Okay, if that's the case, you can make it a generator expression:
Jerub