When passing a function as an argument, sometimes it is more convenient to directly pass an anonymous function instead of explicitly defining one.
Python provides limited support for anonymous functions. Let’s take the map() function as an example again. To calculate f(x) = x^2, besides defining a function f(x), you can directly pass an anonymous function:
>>> list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
[1, 4, 9, 16, 25, 36, 49, 64, 81]
By comparison, the anonymous function lambda x: x * x is actually equivalent to:
def f(x):
return x * x
The keyword lambda denotes an anonymous function, and the x before the colon represents the function parameter.
Anonymous functions have a limitation: they can only contain a single expression. There’s no need to write return, as the return value is simply the result of that expression.
Using anonymous functions offers an advantage: since the function has no name, you don’t have to worry about function name conflicts. Furthermore, an anonymous function is also a function object, so you can assign it to a variable and then call the function using that variable:
>>> f = lambda x: x * x
>>> f
<function <lambda> at 0x101c6ef28>
>>> f(5)
25
Similarly, you can return an anonymous function as a return value, like this:
def build(x, y):
return lambda: x * x + y * y
Rewrite the following code using an anonymous function:
def is_odd(n):
return n % 2 == 1
L = list(filter(is_odd, range(1, 20)))
print(L)
Python’s support for anonymous functions is limited; they can only be used in relatively simple scenarios.