Lambda ====== .. code-block:: ipython 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. .. nextslide:: It's a python object, it can be stored in a list or other container .. code-block:: ipython In [7]: l = [lambda x, y: x+y] In [8]: type(l[0]) Out[8]: function And you can call it: .. code-block:: ipython In [9]: l[0](3,4) Out[9]: 7 Functions as first class objects --------------------------------- You can do that with "regular" functions too: .. code-block:: ipython 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: .. code-block:: ipython 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 --------------------------- .. code-block:: ipython 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!