Lambda Functions in Python

by Dinesh 2012-08-27 13:04:53

Lambda Functions:-


syntax: lambda variable(s) : expression

Sometimes you need to pass a function as an argument, or you want to do a short but complex operation multiple times. You could define your function the normal way, or you could make a lambda function, a mini-function that returns the result of a single expression. The two definitions are completely identical:

1def add(a,b): return a+b
2
3add2 = lambda a,b: a+b

The advantage of the lambda function is that it is in itself an expression, and can be used inside another statement. Here's an example using the map function, which calls a function on every element in a list, and returns a list of the results. (I make a good case below in List Comprehensions that map is pretty useless. It does, however, presents a good one line example.)

1squares = map(lambda a: a*a, [1,2,3,4,5])
2# squares is now [1,4,9,16,25]

Without a lambda, you'd have to define the function separately. You've just saved a line of code and a variable name (for the function).
874
like
0
dislike
0
mail
flag

You must LOGIN to add comments