Odds and Ends
So far, we’ve seen what it takes to write our own functions in Python. There are a handful of additional function-related ideas we’d like to introduce in this section:
lambdacreates anonymous functions.applycalls functions with argument tuples.mapruns a function over a sequence and collects results.Functions return
Noneif they don’t use areturnstatement.Functions present design choices.
Functions are objects, just like numbers and strings.
lambda Expressions
Besides the def statement, Python also provides an
expression form that generates function objects. Because of its
similarity to a tool in the LISP language, it’s called
lambda. Its general form is the keyword
lambda, followed by one or more arguments,
followed by an expression after a colon:
lambda argument1, argument2,... argumentN : Expression using argumentsFunction objects returned by lambda expressions
are exactly the same as those created and assigned by
def. But the lambda has a few
differences that make it useful in specialized roles:
- lambda is an expression, not a statement
Because of this, a
lambdacan appear in places adefcan’t—inside a list constant, for example. As an expression, thelambdareturns a value (a new function), which can be assigned a name optionally; thedefstatement always assigns the new function to the name in the header, instead of returning it as a result.- lambda bodies are a single expression, not a block of statements
The
lambda’s body is similar to what you’d put in a ...
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