Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply a logical operator to all elements in a python list

Tags:

python

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.

like image 264
Robert Christie Avatar asked Nov 24 '09 14:11

Robert Christie


People also ask

How do you use multiple logical operators in Python?

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.

How do you do or operations for a list in Python?

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] .

Can you put operators in a list Python?

Python List can have duplicate elements. They also allow None. List support two operators: + for concatenation and * for repeating the elements.

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.


1 Answers

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

like image 57
fortran Avatar answered Oct 14 '22 17:10

fortran