[Tutor] Built In Functions

Steven D'Aprano steve at pearwood.info
Tue Dec 17 01:45:38 CET 2013


On Mon, Dec 16, 2013 at 05:15:28PM +0000, Alan Gauld wrote:
> On 16/12/13 15:28, Rafael Knuth wrote:
> 
> >First question: all(iterable) and any(iterable) - can you give me one
> >or two examples what these functions do and how they are specifically
> >used?
> 
> In my experience they aren't used all that often. 


I use any() and all() frequently. For example, suppose you have a 
function that takes a list of numbers, and they are all supposed to be 
positive.

def calculate_values(numbers):
    if all(number > 0 for number in numbers):
        # do the calculation
    else:
        raise ValueError("negative or zero number found")


That could be re-written as:

def calculate_values(numbers):
    if any(number <= 0 for number in numbers):
        raise ValueError("negative or zero number found")
    else:
        # do the calculation


> >>> all('')
> True
> 
> Actually the last one surprised me. I expected false. So maybe a 
> resident guru can explain that anomaly...

This is called "Vacuous truth".

http://en.wikipedia.org/wiki/Vacuous_truth

Vacuous truth is a requirement of formal logic, and most of the time it 
is the right thing to do intuitively as well. For example, suppose 
you're given a stack of disks to securely erase, and it just so happens 
that one of those disks was blank and contained no files. When asked, 
"Did you securely erase all the files on each disk?", the intuitively 
correct answer is, "yes".

Unfortunately, there are also cases where we don't want vacuous truths, 
since under some circumstances they can be misleading:

"9 out of 10 nutritionists that we asked agree that Berrilicious Honey 
Sugar Puffs With Added Caffeine is an important part of your child's 
breakfast! (We actually didn't ask any...)"

so there is no universal right or wrong way to handle such things. 
However, in my experience, having all() and any() default to True and 
False respectively in the case of empty input is usually the right 
solution.



-- 
Steven


More information about the Tutor mailing list