any(), all() and empty iterable

Tim Chase python.list at tim.thechases.com
Sun Apr 12 13:53:24 CEST 2009


>>From the docs:
> 
> all(iterable)
>         
>         Return True if all elements of the iterable are true. Equivalent
>         to:
>         
>         def all(iterable):
>             for element in iterable:
>                 if not element:
>                     return False
>             return 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 
in the docs should read "Return False if any element of the 
iterable is not true" or "Return True if all elements of the 
iterable are true or if the iterable is empty."

To get the behavior the original comment describes, would seem to 
require an implementation something like this:

   def all(iterable):
     iterable = iter(iterable)
     try:
       element = iterable.next()
     except StopIteration:
       raise UnderdefinedBecauseNoElementsToCompareToTrue
     while element:
       try:
         element = iterable.next()
       except StopIteration:
         return True
     return False


Tweaking the documentation seems like an easier and more 
backwards compatible solution to me :)

-tkc






More information about the Python-list mailing list