Lambda functionsΒΆ
Some functions can be easily defined in a single line of code, and it is
sometimes useful to be able to define a function “on the fly” using lambda
notation. lambda
is a special way of creating small, single-line
functions. The format of the lambda is:
lambda <arguments>: <single exprsession>
To define a function that returns 2*x
for any input x
, rather
than:
def f(x):
return 2*x
Although lambda functions are anonymous functions, this doesn’t
mean that you can’t give it a name. We can define f
via:
>>> f = lambda x: 2*x
A lambda expression can also have a list:
>>> f = lambda: [x**2 for x in range(10)]
>>> f()
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
You can also define functions of more than one variable, e.g.:
>>> g = lambda x,y: 2*(x+y)
A lambda function can be called after it is defined:
>>> (lambda x, y=10: 2*x + y) (42)
94
A more complicated example which uses a lambda function as a keyword
argument (i.e., f=lambda...
) in another function func
:
>>> def func(vals, f=lambda x: sum(x)/len(x)):
f(vals)
>>> func([1,2,3,4,5])
3
Note
The lambda notation is one of the built-in Python keywords Python keywords, which means importing NumPy is not needed to use it.
Note
One thing you notice here is that the keyword argument f=...
is
supplied optionally. If there are multiple keyword arguments, they
may be called in any order and are not restricted to the order in
which they were originally defined.