any(), all() and empty iterable
arnodel at googlemail.com
Sun Apr 12 18:24:38 CEST 2009
Tim Chase <python.list at tim.thechases.com> writes:
> Arnaud Delobelle wrote:
>> Paul Rubin <http://phr.cx@NOSPAM.invalid> writes:
>>> Tim Chase <python.list at tim.thechases.com> writes:
>>>>> Return True if all elements of the iterable are
>>>>> true. ...
>>>> Then I'd say the comment is misleading. An empty list has no item
>>>> that is true (or false), yet it returns true.
>>> The comment is correct. "All the items of the iterable are true"
>>> means EXACTLY the same thing as "there are no items of the iterable
>>> that are false". The empty list has no false items. Therefore
>>> all(empty_list) = True is the correct behavior.
>>> Another possible implementation:
>>> import operator,itertools
>>> def all(xs):
>>> return reduce(operator.and_, itertools.imap(bool, xs), True)
>> A contest! My entry:
>> def all(iterable):
>> return not sum(not x for x in iterable)
> Problem with both entries: short-circuit evaluation.
> def test_me(how_many=99999999999999999):
> yield False
> for _ in xrange(how_many): yield True
> print all(test_me())
> The stdlib version wisely bails on the first False. A particularly
> useful aspect when test_me() does something time-consuming:
> def test_me(times=100)
> for _ in xrange(times):
> yield some_long_running_process_that_usually_returns_false()
> where that process may do something like slurp a web-page across the
> planet, or calculate some expensive expression.
I was aware of this but I mimicked the behaviour of Paul's
implementation. It's even worse if the iterable is something like
More information about the Python-list