any() and all() on empty list?

Gerard Flanagan grflanagan at yahoo.co.uk
Fri Mar 31 15:11:36 CEST 2006

```Steve R. Hastings wrote:

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

Ant wrote:

> all(list) simply means "every element of the list evaluates to True".
> This is trivially true in the case of the empty list. This is logically
> equivalent to "There are no elements in the list which evaluate to
> False".
>
> any(list) simply means "at least one element of the list evaluates to
> true". This is trivially false for the empty list - there are no
> elements to be true.
>
> These are logical functions and should be mathematically sound. It's
> possible to add all sorts of problems if we just arbitrarily decide
> what "for all x" should mean. We may just as well decide that for
> convenience: math.pi == 3.
>

I agree.

Some amateur maths - applying the identities of a 'two-element Boolean
algebra' found here:

http://en.wikipedia.org/wiki/Two-element_Boolean_algebra

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

#the identities don't hold if you use the alternative
##def all(S):
##    ret_val = False
##
##    for x in S:
##        ret_val = True
##        if not x:
##            return False
##
##    return ret_val

empty = []
universe = [ 0, 1 ]

one = all(empty)
zero = any(empty)

assert (one or one) == one
assert (one or zero) == one
assert (zero or one) == one
assert (zero or zero) == zero
assert (zero and zero) == zero
assert (zero and one) == zero
assert (one and zero) == zero
assert (one and one) == one
assert (not one) == zero
assert (not zero) == one

#on the other hand
one = all(universe)
zero = any(universe)

#de Morgan - swap 'and' and 'or' and complement the result
assert not(one and one) != one
assert not(one and zero) != one
assert not(zero and one) != one
assert not(zero and zero) != zero
assert not(zero or zero) != zero
assert not(zero or one) != zero
assert not(one or zero) != zero
assert not(one or one) != one
assert not(not one) != zero
assert not(not zero) != one

----------------------------------------------------------------------

Gerard

```