any() and all() on empty list?

Ron Adam rrr at ronadam.com
Wed Mar 29 05:10:41 EST 2006


Paul Rubin wrote:
> Ron Adam <rrr at ronadam.com> writes:
>> In this view and empty set can be True for all().  Is it posible
>> 'all([])'  is undefined?  Here, none() and all() return contradicting
>> values.  So maybe the correct version may be...
> 
> I don't see any contradiction.  all([]) and none([]) are both true.

Contradicting wasn't the correct term to use I suppose. And in any case 
it's not really the point at hand. See below.


> Anyway, this has all been discussed before in a slightly different context:

I'm sure it has.  And I don't mean to disagree with the pure 
mathematical or logical meanings.

I'm thinking more in terms of weather or not they are defined correctly 
for their desired usage.  If they are meant to be used as pure logic 
functions in math formulas then of course they should follow the 
mathematical definitions.  But if they are meant to be used as flow 
control tests, then they should follow pythons flow control semantics 
and do what give the best results when used as flow control tests in 
most situations.

Currently:

     not not []      -> False  -> has None
     not not [...]   -> True   -> has Some


So using the same semantics... (With no conditional statements)

# has any True
def any(S):
    result = not not []
    for x in S:
       result = result or x
    return not not result

# has all True
def all(S):
    result = not not S
    for x in S:
       result = result and x
    return not not result

These are 'has any True' and 'has all True' which aren't the same as the 
math operations 'any True' and 'all True'.

But the real questions is, does it do the right thing in real code?

Wouldn't I want to skip a block if the sequence is an empty set?

     while all(S):
        ...

Would I need to prefix some or many tests with a condition or logical 
check for an empty set?

     if S and all(S): foo()

How often would these situations come up?

Could pure logic functions 'anytrue()' and 'alltrue()' live in the math 
module and 'any()' and 'all()' be flow control tests as builtins?

     (Only if there is desire and need for both of course.)

Just thinking about things.  I really just want what is best for Python 
in the long term and am not trying to be difficult.  I haven't seen 
many use cases yet and it seems to me it may make a difference.  So I'm 
going to try to find places in my own code where these will be useful in 
the meantime.

Cheers,
    Ron





















More information about the Python-list mailing list