• Master Python Lambda Functions With These 4 Don ‘ts
  • Yong Cui, Ph.D.
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: loststar
  • Proofreader: luochen1992

Master Lambda functions in Python with the “Four Don ‘ts”

Lambda functions are anonymous functions in Python. When you need to complete a small piece of work, using them in a local environment can be handy. Some people call them lambdas for short, and their syntax is as follows:

lambda arguments: expression
Copy the code

The lambda keyword can be used to create a lambda function, followed by a list of arguments and a single expression separated by a colon. For example, lambda x: 2 * x multiplies any input number by 2, while lambda x, y: x+y computes the sum of two numbers. The syntax is pretty straightforward, right?

Assuming you know what lambda functions are, this article aims to provide some general guidelines on how to use them properly.

1. Do not return any value

Looking at the syntax, you might notice that we don’t return anything in the lambda function. This is all because lambda functions can contain only one expression. However, using the return keyword makes a non-syntactic statement, 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 1
    sorted(integers, key=lambda x: return x[-1])
                                   ^
SyntaxError: invalid syntax
Copy the code

The error may be caused by an inability to distinguish between expressions and statements. Statements such as return, try, with, and if perform special actions. Expressions, however, refer to expressions that can be evaluated to a value, such as numeric values or other Python objects.

By using lambda functions, individual expressions are evaluated to a value and participate in subsequent computations, such as sorted by the sorted function.

2. Don’t forget better options

Lambda functions are most commonly used as arguments to keys in some built-in utility functions, such as sorted() and Max () shown above. Depending on the situation, we can use other alternatives. 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)
Copy the code

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

>>> 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
Copy the code

3. Do not 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 someone do something like this:

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

The only use of naming lambda functions may be for educational purposes, to show that lambda functions really are functions like any other — that they can be called and do something. 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 using the regular DEF keyword, lambda functions have no names, which is why they are sometimes called anonymous functions. Consider the following simple example to pick out 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
Copy the code
  • When your code has questions about lambda functions (i.einversive0),TracebackThe error message simply indicates that there is a problem with the lambda function.
  • By contrast, using normally defined functions,TracebackYou are clearly prompted for the problematic function (i.einversive1).

Related to this, if you want to use lambda functions more than once, the best practice is to use regular functions defined by def that allow docstrings.

4. Don’t forget list derivations

Some people like to use lambda functions 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 the filter function with a lambda function
>>> list(filter(lambda x: x % 2, numbers))
[1.3, -3]
Copy the code

Instead of lambda functions, we can use more readable list derivations. As shown below, we use a list derivation to create the same list object. As you can see, the map or filter functions were more cumbersome to use with lambda functions than list comprehensions. Therefore, consider using list derivations 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]
Copy the code

conclusion

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

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

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.