Practical Uses of Python lambda function
Python Lambda Function with List Comprehension
On each iteration inside the list comprehension, we are creating a new lambda function with a default argument of x (where x is the current item in the iteration). Later, inside the for loop, we are calling the same function object having the default argument using item() and get the desired value. Thus, is_even_list stores the list of lambda function objects.
Python3
is_even_list = [ lambda arg = x: arg * 10 for x in range ( 1 , 5 )] for item in is_even_list: print (item()) |
Output:
10
20
30
40
Python Lambda Function with if-else
Here we are using the Max lambda function to find the maximum of two integers.
Python3
Max = lambda a, b : a if (a > b) else b print ( Max ( 1 , 2 )) |
Output:
2
Python Lambda with Multiple Statements
Lambda functions do not allow multiple statements, however, we can create two lambda functions and then call the other lambda function as a parameter to the first function. Letâs try to find the second maximum element using lambda.
The code defines a list of sublists called âList'
. It uses lambda functions to sort each sublist and find the second-largest element in each sublist. The result is a list of second-largest elements, which is then printed. The output displays the second-largest element from each sublist in the original list.
Python3
List = [[ 2 , 3 , 4 ],[ 1 , 4 , 16 , 64 ],[ 3 , 6 , 9 , 12 ]] sortList = lambda x: ( sorted (i) for i in x) secondLargest = lambda x, f : [y[ len (y) - 2 ] for y in f(x)] res = secondLargest( List , sortList) print (res) |
Output:
[3, 16, 9]
Python Lambda Functions
Python Lambda Functions are anonymous functions means that the function is without a name. As we already know the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python.
Contact Us