[Tutor] Usefulness of BIFs all() and any()?

Hugo Arts hugo.yoshi at gmail.com
Tue Sep 25 14:24:20 CEST 2012

On Tue, Sep 25, 2012 at 1:55 PM, Richard D. Moores <rdmoores at gmail.com>wrote:

> I was just perusing the Built-in Functions of Python 3.2 (<
> http://docs.python.org/py3k/library/functions.html>) and was wondering
> where would one ever use any() or all().
> But so what? Could I get some better examples?

I frequently use any() or all() in combination with a generator expression
to check for a certain condition over a list of elements. Let's say, for
example, I want to make sure all files I used are closed at the end of a
function (or perhaps a unit test?)

assert all(f.closed for f in open_files)

probably not the *most* useful example of that, but I'm sure you understand
the principle. It's useful when you need to check if all() or any() of an
iterator pass a certain condition.

> And why
> >>> all([])
> True
> >>> any([])
> False

People often wonder over this one. any([]) should logically be False,
because it is like asking the question "is there any member in this
iterable that is True?" Obviously, there is not, since the iterator is
empty. all([]) is True by the principle of vacuous truth:


The principle, though somewhat intuitive, has a strong mathematical basis.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120925/0d4590e1/attachment.html>

More information about the Tutor mailing list