[python function] Lambda function of Python

Lambda functions are anonymous functions in Python. When you need to get a small job done, using them in the local environment can make the job handy. Some people refer to them simply as lambdas, and their syntax is as follows:

lambda arguments: expression

lambda keyword can be used to create a lambda function, followed by a list of parameters and individual expressions separated by colons. For example, lambda x: 2 * x instead of multiplying any input number by 2, lambda x, y: x+y it calculates the sum of two numbers. The syntax is pretty straightforward, right?

Assuming you know what a lambda function is, this article aims to provide some general guidelines on how to use lambda functions correctly.

# 1. Do not return any value

Looking at the syntax, you might notice that we didn't return anything in the lambda function. This is all because a lambda function can only contain one expression. However, the use of  return keywords can result in a statement that does not conform to the prescribed syntax, as follows:

>>> integers = [(3, -3), (2, 3), (5, 1), (-4, 4)]
>>> sorted(integers, key=lambda x: x[-1])
[(3, -3), (5, 1), (2, 3), (-4, 4)]
>>> sorted(integers, key=lambda x: return x[-1])
... 
  File "<input>", line 1
    sorted(integers, key=lambda x: return x[-1])
                                   ^
SyntaxError: invalid syntax

The error may be caused by inability to distinguish between expressions and statements. Statements like includes  return, trywith and  ifperform special actions. However, expressions refer to those expressions that can be evaluated to a value, such as numbers or other Python objects.

By using lambda functions, a single expression is evaluated as a value and participates in subsequent calculations, such as  sorted sorting by the function.

# 2. Don't forget about better options

The most common use case for a lambda function is to use it as an argument in some built-in utility functions  , such as  the sum  key shown above  . Depending on the situation, we can use other alternatives. Consider the following example:sorted()max()

>>> integers = [-4, 3, 7, -5, -2, 6]
>>> sorted(integers, key=lambda x: abs(x))
[-2, 3, -4, -5, 6, 7]
>>> sorted(integers, key=abs)
[-2, 3, -4, -5, 6, 7]
>>> scores = [(93, 100), (92, 99), (95, 94)]
>>> max(scores, key=lambda x: x[0] + x[1])
(93, 100)
>>> max(scores, key=sum)
(93, 100)

In the field of data science, many people use the pandas library to process data. As shown below, we can use lambda functions  map() to create new data from existing data through functions. Instead of using lambda functions, we can also use arithmetic functions directly, since pandas supports them:

>>> import pandas as pd
>>> data = pd.Series([1, 2, 3, 4])
>>> data.map(lambda x: x + 5)
0    6
1    7
2    8
3    9
dtype: int64
>>> data + 5
0    6
1    7
2    8
3    9
dtype: int64

# 3. Don't assign it to a variable

I've seen some people mistake lambda functions for just another way of declaring simple functions, and you've probably seen people do things like this:

>>> doubler = lambda x: 2 * x
>>> doubler(5)
10
>>> doubler(7)
14
>>> type(doubler)
<class 'function'>

The only use of naming lambda functions is probably for pedagogical purposes, to show that lambda functions are indeed functions like any other—can be called and do something. Besides that, we should not assign lambda functions to variables.

The problem with naming lambda functions is that it makes debugging less intuitive. Unlike other  def functions created with regular keywords, lambda functions do not have a name, which is why they are sometimes called anonymous functions. Consider the following simple example and spot the subtle differences:

>>> inversive0 = lambda x: 1 / x
>>> inversive0(2)
0.5
>>> inversive0(0)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 1, in <lambda>
ZeroDivisionError: division by zero
>>> def inversive1(x):
...     return 1 / x
... 
>>> inversive1(2)
0.5
>>> inversive1(0)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 2, in inversive1
ZeroDivisionError: division by zero
  • When your code has a problem with the lambda function (ie inversive0), the Traceback error message will only prompt you that there is a problem with the lambda function.

  • In contrast, with a normally defined function, Traceback will clearly prompt you for the problematic function (ie inversive1).

On a related note, if you want to use a lambda function multiple times, the best practice is to use  def a regular function that allows docstrings by definition.

# 4. Don't forget list comprehensions

Some people like to use lambda functions with higher-order functions, such as  map or  filter. Consider the following usage example:

>>> # 创建一个数字列表
>>> numbers = [2, 1, 3, -3]
>>> # 使用带有 lambda 函数的 map 函数
>>> list(map(lambda x: x * x, numbers))
[4, 1, 9, 9]
>>> # 使用带有 lambda 函数的 filter 函数
>>> list(filter(lambda x: x % 2, numbers))
[1, 3, -3]

Instead of lambda functions, we can use more readable list comprehensions. As shown below, we use a list comprehension to create the same list object. map As you can see, using an or  filter function with a lambda function before is more cumbersome than a list comprehension  . Therefore, list comprehensions should be considered when creating lists involving higher-order functions.

>>> # Use list comprehensions
>>> [x * x for x in numbers]
[4, 1, 9, 9]
>>> [x for x in numbers if x % 2]
[1, 3, -3]

# in conclusion

In this article, we review four common mistakes you can make with lambda functions. By avoiding these mistakes, you should be able to use lambda functions correctly in your code.

A rule of thumb with lambda functions is to keep it simple and use it locally only once.

Original address: Master Python Lambda Functions With These 4 Don'ts

Author: Yong Cui, Ph.D.

Permanent link to this article:

https://github.com/xitu/gold-miner/blob/master/article/2020/master-python-lambda-functions-with-these-4-donts.md

Translator: loststar Proofreader: luochen1992

Guess you like

Origin blog.csdn.net/qq_42200107/article/details/126060617