any() and all() on empty list?

Ben Finney bignose+hates-spam at benfinney.id.au
Wed Mar 29 08:57:57 CEST 2006

```"Steve R. Hastings" <steve at hastings.org> writes:

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

And there was much rejoicing.

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

Yep.

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

Not quite how I'd phrase it. I prefer, for symmetry with 'any':

all(seq) returns False if any value in seq evaluates false, True 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():
>
> 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

I love the symmetry of these semantics, find them quite intuitive, and
therefore disagree with your interpretation of 'all()'.

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

-1.

You may as well argue that "any() should be a more restrictive
function than all(), and it bothers me to see a case where all()
returns False but any() returns True."

It seems clear to me that an empty argument list fails a check for
"any True?", because that's the same as a check for "all False?". The
only reasonable alternative would be a special case for an empty
argument list, and that's too ugly.

It seems clear to me that an empty argument list passes a check for
"all True?", because that's the same as a check for "any False?". The
only reasonable alternative would be a special case for an empty
argument list, and that's too ugly.

To imagine that one of these "should be a more restrictive function"
would belie their simple, elegant, and (to me) obvious definitions. I