Python Lambda Tutorial
Lambda expressions are a powerful feature in the Python programming language. However, they can be a little intimidating at first glance, especially since they have no direct equivalent in languages like Java that most programming courses are taught in. These expressions allow the programmer to define unnamed functions on the fly and assign them to a variable name. You can create an array of functions with lambda and assign them all to a single variable name.
Instructions
-
-
1
Define a function with the lambda keyword and assign it to the "sum" variable name.
>>> sum = lambda x,y: x+y
Test to see if your lambda function works with the following command:
>>> sum(2,2)
4This shows the absolute minimum for lambda, but you can do a little more with it.
-
2
Define more than one lambda function to a single variable.
>>> operation = { 'sum':lambda x,y:x+y, 'sub':lambda x,y:x-y, 'mul':lambda x,y:x*y, 'div':lambda x,y:x/y }
>>> operation['sum'] (2,2)
4
>>> operation['mul'] (2,4)
8
>>> operation['div'] (4,4)
1
>>> operation['sub'] (4,1)
3That still doesn't reveal one of the most stunning features of lambda. In fact, more than any other feature, this is the one that generates the most excitement about lambda functions in older languages like LISP which supported it.
-
-
3
Use lambda to, in a single line, perform an operation on every element on a list and return a new list containing the results of the operation.
>>> alist = [ 0, 1, 2, 3, 4 ]
>>> map(lambda x: x*6, alist)
[0, 6, 12, 18, 24]For another example, to find the lengths of all the words in a string, use the following lambda function:
>>> string = "It was a very long day at the office, but when I come home to you, it is all worthwhile."
>>> map(lambda x: len(x), string.split())
[2, 3, 1, 4, 4, 3, 2, 3, 7, 3, 4, 1, 4, 4, 2, 4, 2, 2, 3, 11]This allows a programmer to do, in one short and easy to read line, what a Java programmer would require four or five lines to achieve.
-
1