Simple Ways to Apply Lambda Function in Python | by Chi Nguyen | Towards Data Science

An anonymous function is a function without a name. In Python, an anonymous function is determined using lambda keyword. It is because lambda functions do not require a name when it is defined, unlike regular functions. Instead of using def keyword, we use lambda keyword to construct a function. That’s why the anonymous function is also referred to as the lambda function.
A lambda function can have several arguments but only have one expression. The following syntax is used to declare a lambda function:
lambda argument(s): expression
There are thousands of use cases using lambda functions. However, when function objects are required, they are most often applied.
Moreover, there is no “return” statement in a lambda definition; instead, it always includes a returned expression. Therefore, for simplicity, you can consider using lambda function.
Besides, it is better to use lambda functions when the function expression is small to improve readability. In other words, lambda can only have one expression, hence don’t use a lambda function if your function can’t be stated in a single line of code.
Later, we will explore several examples of using the lambda function to understand its use case better.
I will explain the usage of the lambda function by applying it to different examples. First, let’s create a simple data frame for manipulation.
grade = {'Class':['A1', 'A2', 'A3', 'A4','A5'],        'MathScore':[3.2, 3.3, 2.1, 2.9, 3.6],        'ChemistryScore': [3.2, 3.6,3.3,2.1,4.6]}grade = pd.DataFrame(grade)
The dataset illustrates average scores of Maths and Chemistry for five classes from A1 to A5.
For example, I want to evaluate the Mathematical ability of each class based on a special formula, which is getting the Math score to the power of the Math score itself, then dividing the result by 2. Here is how I compute by using lambdafunction.
grade['evaluate']=grade['MathScore'].apply(lambda x: round((x**x)/2,2))
The apply method calls lambda function, and applies the computation to each row of the data frame. Besides, apply can also do the modification for every column in the data frame. In that case, specify one more argument as axis = 0 in the apply function. My result after the calculation is stored in the “evaluate” column, as you can see below.
Output:
In another example with our data frame (Figure 1) above, I want to categorize classes based on their performances in Maths and Chemistry. We can use lambda to figure that out easily.
grade['group']=grade['MathScore'].apply(lambda x: 'Excellent' if x>=3.0 else 'Average')
Output:
Suppose I have a list as below:
list = [[5,6],[12,32,43],[3,43,42]]
To find the sub-list with maximum values, I may apply lambda function and maxas follows:
max(list, key=lambda x: sum(x))
As a result, [3,43,42] is the sub-list with the highest total value among the three sub-lists.
In case I want to make a comparison between values and get the result of a greater value. Let’s see how we can make it happen with lambda and if-else.
Greater = lambda x, y : x if(x > y) else yGreater(0.002, 0.5897)
And the result turns out to be 0.5897. Simple, right?
Continue to use the example data frame from figure 1, I will find out how many Math scores are greater than the average score. The filter method can filter the data by applying lambda function to the series. Here is how it goes:
mean = mean(grade['MathScore'])list(filter(lambda x: x> mean,grade['MathScore']))
And the output is a list of math scores that are greater than its mean: [3.2, 3.3, 3.6]
In another case, I want to find the intersection for nested lists with filter method. See what I have in two lists below:
group1 = [1, 2,3,43,23,42,8,3,7]group2 = [[3, 34, 23, 32, 42], [6, 11, 9], [1, 3,9,7,2,8]]
Now, by applying the following code, I can find out a list in which values in group 2 are also present in group 1:
[list(filter(lambda x: x in group1, sublist)) for sublist in group2]
Output: [[3, 23, 42], [], [1, 3, 7, 2, 8]]
To shortly explain, the filter method examines each sub-list’s item to determine if it is included in group 1. The list comprehension is applied to each sub-list in group 2.
Above are some simple examples of lambda.I hope you find them useful. If you have any interesting applications, don't hesitate to share them with me.