any(), all() and empty iterable

Albert Hopkins marduk at letterboxes.org
Sun Apr 12 00:39:11 EDT 2009


On Sun, 2009-04-12 at 04:00 +0000, John O'Hagan wrote:
> Hi,
> 
> I was getting some surprising false positives as a result of not expecting 
> this:
> 
> all(element in item for item in iterable)
> 
> to return True when 'iterable' is empty. 
> 
> I guess it goes into hairy Boolean territory trying to decide if an element is 
> in an item that doesn't exist (if that's what's happening), but I would have 
> thought not. It seems inconsistent with the behaviour of
> 
> any(element in item for item in iterable)
> 
> which returns False when 'iterable' is empty.
> 
>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
        
        
any(iterable)
        
        Return True if any element of the iterable is true. Equivalent
        to:
        
        def any(iterable):
            for element in iterable:
                if element:
                    return True
            return False
        
        
> Sorry if this has come up before, but 'any' and 'all' make for fruitless 
> googling!

Try Googling for:

"any site:docs.python.org"






More information about the Python-list mailing list