Doing More with Functions
This section discusses more advanced features, which you may prefer to skip on the first time through this chapter.
Functions As Arguments
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 another 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 functions, so-called lambda
expressions. Supposing there was no need to use the
last_letter() function in multiple places, and thus no need ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access