andmap and ormap

Peter Otten __peter__ at web.de
Tue Mar 14 07:58:44 EST 2006


wkehowski at cox.net wrote:

> def ormap(b,L):
>   if True in map(b,L): return True
>   else: return False
> 
> Is this good enough?

No, because 

- (as Felipe observed) it doesn't shortcut, i. e. it always evaluates
b(item) for all items in L. 
- it creates a temporary list
- if truthvalue: return True
  else: return False
  is redundant and just plain ugly

Just write
  
return truthvalue

or, when truthvalue may consume a lot of memory,
  
return bool(truthvalue) # or: return not not truthvalue

Which gives:

def andmap(predicate, items):
    return False not in (predicate(item) for item in items)
        
def ormap(predicate, items):
    return True in (predicate(items) for item in items)
        

> andmap((lambda t: boolean(t)),L)

Superfluous lambda alert: make that

andmap(boolean, L)

Python 2.5 will feature similar functions any() and all() which seem to have
a fixed predicate == bool, though.

Peter



More information about the Python-list mailing list