On 12/16/2013 04:28 PM, 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?

Thank you!

'all' and 'any' only are a bit obscure because of their actual implementation. The intent is of functions that say whether all items (or each or every), or any item (or some), in a list or any other "iterable" (sequence) satisfy a criterion. This is very much like the modal operators "for each" (an 'A' upside down) and "there exists" (an 'E' upside down) in mathematical logic. The logic (sic!) would thus be like:

def every (collection, criterion):
    for item in collection:
        if not criterion(item):
            return False
    return True

def some (collection, criterion):
    for item in collection:
        if criterion(item):
            return True
    return False

def is_odd (n): return (n%2 == 1)       # our criterion

l1 = [1,3,5,7,9]
l2 = [2,4,5,7,8]
l3 = [2,4,6,8]

print(every(l1, is_odd))
print(every(l2, is_odd))
print(every(l3, is_odd))

print(some(l1, is_odd))
print(some(l2, is_odd))
print(some(l3, is_odd))

==>

True
False
False
True
True
False

For each item, we first get a logical value telling whether it satisfies the criterion. Then, we operate on this result -- differently for each function.

However, Python's 'all' and 'any' actually operate on sequences that are supposed to _already_ contain boolean (logical) value; as if the sequences, instead of holding their original items, were already converted into derived sequences holding the results of applying the criterion. We could do this using either map or comprehensions:

l1      = [1,3,5,7,9]
# sequences of logical values:
l1_map  = map(criterion, l1)
l1_comp = (criterion(it) for it in l1)

Similarly for l2 & l3. Then, we can apply Python's builtin 'all' and 'any'.

print(all(l1_map))
print(any(l1_map))

Does this help?

Denis

















_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to