[Tutor] Usefulness of BIFs all() and any()?
steve at pearwood.info
Tue Sep 25 15:41:53 CEST 2012
On 25/09/12 21:55, Richard D. Moores 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().
Both are very useful. They are especially useful for validating data, or
for interactive use. For instance, to check that a list of numbers are
if all(x > 0 for x in numbers): ...
and then go on to process the numbers.
There are over a dozen examples of any or all in the Python standard
library. (There would be more, but a lot of the std lib pre-dates the two
functions.) They tend to be used to check the state of some collection of
values, and return a flag. For example:
return any(key in m for m in self.maps)
checks whether a key appears in a collection of maps. Otherwise that one
line would be written as:
for m in self.maps:
if key in m:
Notice the pattern there is that if the collection of maps is empty, then
you return False. And sure enough, any() returns False.
In an example from my own code, I have a pool of threads doing work, and
loop until all of the threads have finished:
while any(t.isAlive() for t in threads): ...
Another example, I check that a list of objects are all integers:
if not all(isinstance(i, int) for i in key): ...
Basically, the functions all and any should be used whenever you need to
check that a condition holds for ALL the values, or for ANY value, in a
collection of values. If they sound like trivial functions, well, yes,
they are trivial like a hammer is trivial. It's just a lump of metal used
for bashing in nails.
> And why
Because they match the most useful and common patterns for testing that
some condition holds. Normally we want to test:
* there is at least one value where this condition holds (use any)
* there are no values at all, or there is at least one value...
Imagine the set of living people with no heads. If any of them are called
"Steve", you pay me a dollar. Do you owe me anything?
The case for all() returning True is a bit less obvious. One of the first
things I did in my own code was write an alternative version of all:
magic = object()
element = magic
for element in iterable:
if not element:
return element is not magic
but I've never used it.
More information about the Tutor