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 cube(3)
Using Lambda Functions
cube = lambda x : x*x*x cube(3)
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) filtered_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) mapped_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) reduce
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.