So far the arguments we have passed into functions have been simple objects, such as
strings, or structured objects, such as lists. Python also lets us pass a function as an
argument to another function. Now we can abstract out the operation, and apply a
different operation on the same data. As the following examples show, we can pass the
built-in function len() or a user-defined function last_letter() as arguments to an
other function:
sent = [‘Take’, ‘care’, ‘of’, ‘the’, ‘sense’, ‘,’, ‘and’, ‘the’,
… ‘sounds’, ‘will’, ‘take’, ‘care’, ‘of’, ‘themselves’, ‘.’]def extract_property(prop):
… return [prop(word) for word in sent]
…extract_property(len)
[4, 4, 2, 3, 5, 1, 3, 3, 6, 4, 4, 4, 2, 10, 1]def last_letter(word):
… return word[-1]extract_property(last_letter)
[‘e’, ‘e’, ‘f’, ‘e’, ‘e’, ‘,’, ‘d’, ‘e’, ‘s’, ‘l’, ‘e’, ‘e’, ‘f’, ‘s’, ‘.’]
The objects len and last_letter can be passed around like lists and dictionaries. Notice
that parentheses are used after a function name only if we are invoking the function;
when we are simply treating the function as an object, these are omitted.
Python provides us with one more way to define functions as arguments to other func
tions, so-called lambda expressions. Supposing there was no need to use the last_let
ter() function in multiple places, and thus no need to give it a name. Let’s suppose we
can equivalently write the following:
extract_property(lambda w: w[-1])
[‘e’, ‘e’, ‘f’, ‘e’, ‘e’, ‘,’, ‘d’, ‘e’, ‘s’, ‘l’, ‘e’, ‘e’, ‘f’, ‘s’, ‘.’]
Our next example illustrates passing a function to the sorted() function. When we call
the latter with a single argument (the list to be sorted), it uses the built-in comparison
function cmp(). However, we can supply our own sort function, e.g., to sort by de
creasing length.
sorted(sent)
[‘,’, ‘.’, ‘Take’, ‘and’, ‘care’, ‘care’, ‘of’, ‘of’, ‘sense’, ‘sounds’,
‘take’, ‘the’, ‘the’, ‘themselves’, ‘will’]sorted(sent, cmp)
[‘,’, ‘.’, ‘Take’, ‘and’, ‘care’, ‘care’, ‘of’, ‘of’, ‘sense’, ‘sounds’,
‘take’, ‘the’, ‘the’, ‘themselves’, ‘will’]sorted(sent, lambda x, y: cmp(len(y), len(x)))
[‘themselves’, ‘sounds’, ‘sense’, ‘Take’, ‘care’, ‘will’, ‘take’, ‘care’,
‘the’, ‘and’, ‘the’, ‘of’, ‘of’, ‘,’, ‘.’]
