Saturday, April 28, 2012

Lambda in Python

Lambda in Python is the function building tool. In Python you can build functions either by "def" or by "lambda" keywords. Lambda functions are extremely useful in building GUI applications using Tkinter. Lambda is extremely useful in these cases :
  • When the lambda function is being used only once.
  • When a function takes another function as parameter like in filter() , map() and reduce() functions.
  •  When you want your code to be clearer and cleaner.  

Normal Function definition using "def"

def cube(x):
    return x*x*x

Using Lambda Functions

cube = lambda x : x*x*x

Both the above code snippets achieve a similar task of finding the cube. 
As you can see lambda syntax is cleaner. No return statement required.

Lambda's are used extensively in functions such as filter() , map() and reduce() which need function objects as parameters.


It is used to filter the list on some condition. It does return the filtered list.

list = [1,2,3,4,5,6]
filtered_list = filter(lambda x : x%2 ==0 ,list)

The Output is [2,4,6] as it is filtered.Note the use of lambda function passed as parameter.It filters only multiples of 2.


This function is used to map the list to some other list. Mutate the values of one list and generate another list.

list = [1,2,3,4,5]
mappped_list = map(lambda x:x**2,list)
The output is [1,4,9,16,25] . The values in the list are mapped to their squares generating mapped_list.


This function is used to reduce the list to a value. It takes the first two values in a list ,operates on them (depending on the lambda definition) and then he result of the first two is used to operate on the third and so on.

list = [1,2,3,4,5]
reduce = reduce(lambda x,y:x*y , list)
The output is 120 as (1*2 = 2 * 3 =6 *4 =24 *5 =120 ). Observe that lambda takes two parameters x and y and reduces the list to a value based on the definition of the lambda function.
This function seems to be deprecated in Python 3.0.

Lambda's are use once Throw away functions.  
Lambda's return function objects.
Lambda use cases are very rare but make the code a lot cleaner.

Note : If you do have any specific use cases for Lambda's which you have implemented or used in you project ,Please Let me . Do leave a comment.


jmerk said...

I often use them for sorting, for example, a list of tuples by one of the values, like a list:

people = [(person1, age_person1), (person2, age_person2)...]

people.sort(key=lambda x: x[1])

to sort by their age

Samus_ said...

I always use them for sorted() cmp or list.sort() cmp, also for composing large generator expressions.

ychaouche said...

I use it in functionnal programming tools like map, reduce and filter. Example :