any() and all() on empty list?

Steve R. Hastings steve at hastings.org
Wed Mar 29 00:32:51 EST 2006


So, Python 2.5 will have new any() and all() functions.
http://www.python.org/dev/peps/pep-0356/


any(seq) returns True if any value in seq evaluates true, False otherwise.

all(seq) returns True if all values in seq evaluate true, False otherwise.

I have a question: what should these functions return when seq is an empty
list?



Here is Guido's original article where he suggested any() and all():
http://www.artima.com/weblogs/viewpost.jsp?thread=98196

He offered this sample code for the semantics of any() and all():



def any(S):
    for x in S:
        if x:
            return True
    return False

def all(S):
    for x in S:
        if not x:
            return False
    return True



And he pointed out how nifty it is to combine generator functions with
these two new functions:


any(x > 42 for x in S)     # True if any elements of S are > 42
all(x != 0 for x in S)     # True if all elements if S are nonzero



I'm completely on board with the semantics for any().  But all() bothers
me.  If all() receives an empty list, it will return True, and I don't
like that.  To me, all() should be a more restrictive function than any(),
and it bothers me to see a case where any() returns False but all()
returns True.

In the all() example, if there *are* no values in S, then none of the
values can be != 0, and IMHO all() should return False.

Therefore, I propose that all() should work as if it were written this way:

def all(S):
    ret_val = False

    for x in S:
        ret_val = True
        if not x:
            return False

    return ret_val


Comments?

P.S. I searched with Google, and with Google Groups, trying to find
anyplace this might have been discussed before.  Apologies if this has
already been discussed and I missed it somehow.
-- 
Steve R. Hastings    "Vita est"
steve at hastings.org    http://www.blarg.net/~steveha




More information about the Python-list mailing list