[Tutor] Built In Functions

Peter Otten __peter__ at web.de
Mon Dec 16 18:04:24 CET 2013


Rafael Knuth wrote:

> Hey there,
> 
> I am currently looking into all built in functions in Python 3.3.0,
> one by one, in order to understand what each of them specifically does
> (I am familiar with some of them already, but most built in functions
> are still alien to me). I am working with the Python documentation
> http://docs.python.org/3/library/functions.html#all but not all
> examples are clear & self explaining to me as a novice to programming.
> 
> 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?

Take a look at the example implementation in the documentation:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True


It's just a for-loop containing a test. You can use it to perform a test on 
every item in a sequence and it'll do the obvious thing:

>>> all(color == "red" for color in ["red", "red", "red"])
True
>>> all(color == "red" for color in ["red", "green", "blue"])
False

There are interesting corner cases:

>>> all(color == "red" for color in [])
True

So all colors in an empty list are "red". Or "blue"?

>>> all(color == "blue" for color in [])
True

In short, all() applied to an empty sequence is always true.
Also, when an item in a sequence is not true no further tests are performed:


>>> from itertools import count
>>> all(n < 10 for n in count())
False

count() is a (conceptually) infinite sequence of integers starting with 0, 
but only the first 11 items are checked -- we have one item >= 10 and need 
look no further.

By the way, do you note the similarity to the is_prime() function in your 
previous question?

def is_prime(number):
    for element in range(2, number):
        if number % element == 0:
            return False
    return True

You can use all() as a building block for an alternative implentation:

def is_prime(number):
   return all(number % element != 0 for element in range(2, number))


With that in mind and the example implementation in the docs -- can you 
guess what any() does?

Try to figure out the result of

any([False, 0, ""])
any([])
any(color=="green" for color in ["red", "green", "blue"])

How many tests will any() need to perform to determine the result of the 
last expression? 
Can you implement is_prime() using any()?



More information about the Tutor mailing list