Wednesday, January 27, 2010

Python: How useful are lambda functions ?

Lets say you have this function defined:
def square1(x) : return x*x

We can check what square is:
>>> type(square1)
 

And use it like this:
>>>square1 (8)
64

It can be rewritten as an anonymous function or lamda as:
square2 = lamda x: x*x

and again when we check the type we get
>>> type(square2)
 

And it works the same way as the previous function
>>>square2 (8)
64

Now say we define a list:
list = [1,2,3,4,5,6,7,8]

and then we want to get the square of each number. Either of these will work:
>>> map (square1, list)
[1, 4, 9, 16, 25, 36, 49, 64]

and same result with
>>> map (square2, list)
[1, 4, 9, 16, 25, 36, 49, 64]

So far the benefit of leaning lambda functions is small. We have only used them to write a small function on the fly and the function has to be small as lambdas do not support multiple statements.

Perhaps the main motivation for lambdas can be illustrated with the following:
strategy = {
    'square' : lambda x: x*x,
    'double' : lambda x: x*2,
    'half'   : lambda x: x/2,
}
list = [1,2,3,4,5,6,7,8]
while(True):
    try:
        x =  raw_input("What would you like to do with the list ? ")
        map(strategy[x], list)
    except KeyError, e:
        print "The value entered is not valid: " + str(e)

The dict called strategy contains 3 lambda functions and if we had not used lambdas the we would have had to add the following lines:

def square(x) : return x*x
def double(x) : return x*2
def half(x)   : return x/x

If our strategy dict contained a lot more functions, it would start getting tedious to define all of these and then since the definition of the function would be in another part of the code, it would not be as quick and easy to see what 'square' does for example.

No comments: