(Star the machine learning algorithm and Python learning to improve AI skills)
Original address: Master Python Lambda Functions With These 4 Don'ts
Original author: Yong Cui, Ph.D.
Translation from: Nuggets Translation Project
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
Lambda functions are anonymous functions in Python. When you need to complete a small job, using them in the local environment can make the job handy. Some people refer to them as lambdas for short, and their syntax is as follows:
lambda arguments: expression
The lambda
keyword can be used to create a lambda function, followed by a list of parameters and a single expression separated by a colon. For example, lambda x: 2 * x
is to multiply any input number by 2, and lambda x, y: x+y
is to calculate 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.
Looking at the syntax, you may notice that we did not return anything in the lambda function. This is because a lambda function can only contain one expression. However, using the return
keyword will constitute a statement that does not conform to the prescribed syntax, as shown below:
>>> 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 1sorted(integers, key=lambda x:return x[-1])^
SyntaxError: invalid syntax
The error may be caused by the inability to distinguish between expressions and statements. For example, statements containing return
, try
, with
, and if
perform special actions. However, expressions refer to those expressions that can be calculated to a value, such as numeric values or other Python objects.
By using the lambda function, a single expression will be calculated as a value and participate in subsequent calculations, such as sorting by the sorted
function.
The most common usage scenario of lambda function is to use it as the actual parameter of key
in some built-in utility functions, such as sorted()
and max()
shown above. Depending on the situation, we can use other alternative methods. Consider the following example:
>>> 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 the lambda function to create new data from existing data through the map()
function. In addition to using lambda functions, we can also directly use arithmetic functions, because pandas supports:
>>> import pandas as pd
>>> data = pd.Series([1,2,3,4])>>> data.map(lambda x: x +5)06172839
dtype: int64
>>> data +506172839
dtype: int64
I have seen some people mistake a lambda function for another way of declaring a simple function, and you may have seen someone do it like this:
>>> doubler = lambda x:2* x
>>> doubler(5)10>>>doubler(7)14>>>type(doubler)<class'function'>
The only effect of naming lambda functions may be for educational purposes, to show that lambda functions are indeed the same functions as other functions-they can be called and have certain functions. In addition, we should not assign lambda functions to variables.
The problem with naming lambda functions is that it makes debugging less intuitive. Unlike other functions created with the regular def
keyword, lambda functions have no names, which is why they are sometimes called anonymous functions. Consider the following simple example to find 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):...return1/ 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
inversive0
), the Traceback
error message will only prompt you that there is a problem with the lambda function.Traceback
will clearly prompt you the problematic function (ie inversive1
).Related to this, if you want to use lambda functions multiple times, the best practice is to use regular functions defined by def
that allow the use of docstrings.
Some people like to use lambda functions together with higher-order functions, such as map
or filter
. Consider the following usage example:
>>> # Create a list of numbers
>>> numbers =[2,1,3,-3]>>> #Use map function with lambda function
>>> list(map(lambda x: x * x, numbers))[4,1,9,9]>>> #Use filter function with lambda function
>>> list(filter(lambda x: x %2, numbers))[1,3,-3]
We can use more readable list comprehensions instead of lambda functions. As shown below, we use list comprehensions to create the same list object. As you can see, it is more troublesome to use the map
or filter
function together with the lambda function before compared to the list comprehension. Therefore, when creating lists involving higher-order functions, you should consider using list comprehensions.
>>> # 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 this article, we reviewed four common mistakes that can be made when using lambda functions. By avoiding these errors, you should be able to use lambda functions correctly in your code.
The rule of thumb for using lambda functions is to keep it simple and use it locally only once.