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]

Lambda functions can be used along with built-in functions like filter(), map() and reduce().

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

Similar Reads

Python Lambda Function Syntax

Syntax: lambda arguments : expression This function can have any number of arguments but only one expression, which is evaluated and returned. One is free to use lambda functions wherever function objects are required. You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression. It has various uses in particular fields of programming, besides other types of expressions in functions....

Python Lambda Function Example

In the example, we defined a lambda function(upper) to convert a string to its upper case using upper()....

Use of Lambda Function in Python

...

Practical Uses of Python lambda function

Let’s see some of the practical uses of the Python lambda function....

Using lambda() Function with filter()

...

Using lambda() Function with map()

...

Using lambda() Function with reduce()

Python Lambda Function with List Comprehension...

Contact Us