I have a list of booleans in python. I want to AND (or OR or NOT) them and get the result. The following code works but is not very pythonic.
def apply_and(alist): if len(alist) > 1: return alist[0] and apply_and(alist[1:]) else: return alist[0]
Any suggestions on how to make it more pythonic appreciated.
To evaluate complex scenarios we combine several conditions in the same if statement. Python has two logical operators for that. The and operator returns True when the condition on its left and the one on its right are both True . If one or both are False , then their combination is False too.
To perform logical “OR”, use the built-in Python function any() , and. To perform logical “NOT”, use a list comprehension statement [not x for x in list] .
Python List can have duplicate elements. They also allow None. List support two operators: + for concatenation and * for repeating the elements.
With * operator The * operator can repeat the same value required number of times. We use it to create a list with a Boolean value.
Logical and
across all elements in a_list
:
all(a_list)
Logical or
across all elements in a_list
:
any(a_list)
If you feel creative, you can also do:
import operator def my_all(a_list): return reduce(operator.and_, a_list, True) def my_any(a_list): return reduce(operator.or_, a_list, False)
keep in mind that those aren't evaluated in short circuit, whilst the built-ins are ;-)
another funny way:
def my_all_v2(a_list): return len(filter(None,a_list)) == len(a_list) def my_any_v2(a_list): return len(filter(None,a_list)) > 0
and yet another:
def my_all_v3(a_list): for i in a_list: if not i: return False return True def my_any_v3(a_list): for i in a_list: if i: return True return False
and we could go on all day, but yes, the pythonic way is to use all
and any
:-)
By the way, Python has not tail recursion elimination, so don't try to translate LISP code directly ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With