6.11 Anonymous functions
In the last section, I defined four helper arithmetic functions and stored
them in a dictionary. After that, I never needed their names again. Python provides lambda
to let you create a function anonymously.
Instead of
def adder(x, y): return x + y
def subtracter(x, y): return x - y
def multiplier(x, y): return x * y
def divider(x, y): return x / y
operations = {
"+": adder,
"-": subtracter,
"*": multiplier,
"/": divider
}
do this:
operations = {
"+": lambda x, y: x + y,
"-": lambda x, y: x - y,
"*": lambda x, y: x * y,
"/": lambda x, y: x / y
}
operations["-"](12.4, 0.4)
12.0
A lambda
function should contain one expression. Python
evaluates the expression and returns the result. Don’t use return
, and don’t put parentheses around the parameters.
If you plan to...