Lambda¶
In [171]: f = lambda x, y: x+y
In [172]: f(2,3)
Out[172]: 5
Content of function can only be an expression – not a statement
Anyone remember what the difference is?
Called “Anonymous”: it doesn’t get a name.
It’s a python object, it can be stored in a list or other container
In [7]: l = [lambda x, y: x+y]
In [8]: type(l[0])
Out[8]: function
And you can call it:
In [9]: l[0](3,4)
Out[9]: 7
Functions as first class objects¶
You can do that with “regular” functions too:
In [12]: def fun(x,y):
....: return x+y
....:
In [13]: l = [fun]
In [14]: type(l[0])
Out[14]: function
In [15]: l[0](3,4)
Out[15]: 7
A bit more about lambda¶
It is very useful for specifying sorting as well:
In [55]: lst = [("Chris","Barker"), ("Fred", "Jones"), ("Zola", "Adams")]
In [56]: lst.sort()
In [57]: lst
Out[57]: [('Chris', 'Barker'), ('Fred', 'Jones'), ('Zola', 'Adams')]
In [58]: lst.sort(key=lambda x: x[1])
In [59]: lst
Out[59]: [('Zola', 'Adams'), ('Chris', 'Barker'), ('Fred', 'Jones')]
lambda in keyword arguments¶
In [186]: l = []
In [187]: for i in range(3):
l.append(lambda x, e=i: x**e)
.....:
In [189]: for f in l:
print(f(3))
1
3
9
Note when the keyword argument is evaluated: this turns out to be very handy!