Five Uses of Lambda Function in Python

  • 2021-10-16 02:12:26
  • OfStack

Catalog introduction 1. Naming use 2. Match with higher-order functions 3. Give "key" parameter 4. Call immediately 5. Use summary in closures

Introduction

Lambda functions (also known as anonymous functions) are one of the core concepts in functional programming.

Python, which supports multiple programming paradigms, also provides a simple way to define lambda functions.

The template for writing lambda functions in Python is:


lambda arguments : expression

It consists of three parts:

· Lambda keyword

The arguments that the function will receive

Expression whose result is the return value of the function

Because of its simplicity, the lambda function can make our Python code more elegant in some usage scenarios. This article demonstrates five common uses of the lambda function in Python and explains them with interesting examples.

1. Naming uses

If we only need a simple function, lambda is a good choice, because it can be regarded as a simpler way to define a function. Therefore, we can give it a name and use it like ordinary function 1.


lambda_add_ten = lambda x: x + 10
print(lambda_add_ten(5))
# 15
 
def add_ten(x):
 return x + 10
print(add_ten(5))
# 15

As the above example shows, the results of the add_ten () and lambda_add_ten () methods are the same, but the lambda function makes our code shorter and clearer.

2. Cooperate with higher order functions

If we can use the lambda function with higher-order functions such as map (), filter (), and reduce (), the program will become more elegant.

Let's look at the following question:

Give you a list below. Can you print all the odd numbers in it?


numbers = [1, 12, 37, 43, 51, 62, 83, 43, 90, 2020]

This question seems simple, but it is enough to distinguish between junior and advanced Python developers.

Beginner programmers may write the following code:


odd_number = []
for n in numbers:
 if n % 2 == 1:
 odd_number.append(n)
print(odd_number)
# [1, 37, 43, 51, 83, 43]

It works normally without any problems. However, an advanced Python programmer only needs one line of code to do the same thing:


print(list(filter(lambda x: x % 2 == 1, numbers)))
# [1, 37, 43, 51, 83, 43]

It looks more elegant, doesn't it?

Incidentally, the above 1-line solution is just to show how to use the lambda function. Of course, there are other single-line solutions, such as list parsing:


odd_numbers = [i for i in numbers if i % 2 == 1]

In fact, in many cases, list connotation functions may be more readable than higher-order functions in collaboration with lambda functions.

3. Assign the "key" parameter

Some built-in methods have key parameters, which provide us with more flexibility.

For example, when we use the sorted () or sort () methods to sort an iteration in Python, the key parameters determine how the two elements in the iteration are compared.

This is also the performance time of lambda function.


leaders = ["Warren Buffett", "Yang Zhou", "Tim Cook", "Elon Musk"]
print(leaders)
# ['Warren Buffett', 'Yang Zhou', 'Tim Cook', 'Elon Musk']
leaders.sort(key=lambda x: len(x))
print(leaders)
# ['Tim Cook', 'Yang Zhou', 'Elon Musk', 'Warren Buffett']

As mentioned above, if we sort the leaders list by the length of each name, a simple way is to pass an lambda function to the key parameter.

Another common usage scenario is to sort dictionaries according to their keys or values.


leaders = {4: "Yang Zhou", 2: "Elon Musk", 3: "Tim Cook", 1: "Warren Buffett"}
print(leaders)
# {4: 'Yang Zhou', 2: 'Elon Musk', 3: 'Tim Cook', 1: 'Warren Buffett'}
leaders = dict(sorted(leaders.items(), key=lambda x: x[0]))
print(leaders)
# {1: 'Warren Buffett', 2: 'Elon Musk', 3: 'Tim Cook', 4: 'Yang Zhou'}

4. Call immediately

The function expression called immediately (IIFE) is an idiom in JavaScript. The lambda function in Python also supports this technique. We can run an lambda function immediately, as follows:


>>> (lambda x,y:x*y)(2,3)
6

However, for the sake of readability and maintainability, it is best to use this technique only in the interactive interpreter of Python.

By the way, if you are familiar with the underlining technique in Python, you can also use the following methods.


>>> lambda x,y:x*y
<function <lambda> at 0x7fc319102d30>
>>> _(2,3)
6

5. Use the

Closures are a powerful functional programming feature that can also be used in Python. Because it is about nested functions, we can use the lambda function to make the program clearer.

Here is an example of using closures:


lambda_add_ten = lambda x: x + 10
print(lambda_add_ten(5))
# 15
 
def add_ten(x):
 return x + 10
print(add_ten(5))
# 15
0

How can we use the lambda function to simplify the above code?


lambda_add_ten = lambda x: x + 10
print(lambda_add_ten(5))
# 15
 
def add_ten(x):
 return x + 10
print(add_ten(5))
# 15
1

As the above example shows, when we use nested functions, the lambda function can help us write more readable and clear code.

Summarize

The lambda function in Python gives us more flexibility and method design options. In a word, we should be familiar with the above five common usages so that we can use them correctly, not overuse them.


Related articles: