any() and all() on empty list?

Steve R. Hastings steve at hastings.org
Wed Mar 29 20:49:24 CEST 2006


On Wed, 29 Mar 2006 21:34:08 +1000, Steven D'Aprano wrote:
> While the implemented behaviour might be more practical than the
> alternatives, it is still worrying paradoxical. If "All sheep are woolly",
> then obviously it must also be true that "Any sheep is woolly". More
> formally, if all(X), then any(X) -- except for the case of empty X. Hmmm.

It seems strange, but Tim Peters explained it well.  It would also seem
strange if this didn't work:

all(lst0) and all(lst1) == all(lst0 + lst1)

Clearly that should work, and it shouldn't fail just because one of the
lists happens to be empty.



If you are working with a list, you can just do this:

lst and all(lst)

What bothers me is the iterator case.  There is no simple way to write a
test like the above if you have an iterator.

Hmmm.  How about this?


def truecount(seq):
    count_true = 0
    count= 0
    for x in seq:
        if x:
            count_true += 1
        count += 1
    return count_true, count



count_true, count = truecount(enough_evidence(x) for x in suspected_attacks)
if not count:
    print "Walk free!"
elif count == count_true:
    print "Send him to Gitmo!"
else:
    print "%d proven attacks out of %d suspected" % (count_true, count)
    if float(count_true) / float(count) >= 0.8:
        print "preponderance of evidence!"



The good thing is that these are simple functions that you can write for
yourself.  I'm happy any() and all() will be built in, but I don't know
that there is sufficient need for truecount() or anything similar.  If you
need it, just write it.
-- 
Steve R. Hastings    "Vita est"
steve at hastings.org    http://www.blarg.net/~steveha




More information about the Python-list mailing list