and [True,True] --> [True, True]?????

jazbees jazbees at gmail.com
Sat Apr 25 17:18:22 CEST 2009


I'm surprised to see that the use of min and max for element-wise
comparison with lists has not been mentioned.  When fed lists of True/
False values, max will return True if there is at least one True in
the list, while min will return False if there is at least one False.
Going back to the OP's initial example, one could wrap a min check on
each list inside another min.

>>> A = [False, True]
>>> B = [True, True]
>>> min(A)
False
>>> min(B)
True
>>> min(min(A), min(B))
False

In a recent work project, I made use of this behavior to condense the
code required to test whether any item in a list of strings could be
found in another string.  Here's a variation on that concept that
checks to see if a string contains any vowels:

>>> hasvowels = lambda x:max([y in x for y in "aeiou"])
>>> hasvowels("parsnips")
True
>>> hasvowels("sfwdkj")
False

If using Python 2.5 or later, this could be combined with Python's
version of the ternary operator if your code is such that the source
list may be empty, which is what I ended up using for my project.

>>> foo = ["green", "orange"]
>>> bar = ["blue", "green", "red", "yellow"]
>>> found = lambda x,y:max([z in y for z in x] if x else [False])
>>> found(foo, bar)
True
>>> foo = []
>>> found(foo, bar)
False



More information about the Python-list mailing list