Introduction to lambda functions in Python

  • 2020-12-10 00:46:49
  • OfStack

The Lambda function, or Lambda expression (lambda expression), is an anonymous function (one that doesn't have a function name). The Lambda expression is based on the mathematical name and directly corresponds to the lambda abstraction (lambda abstraction).

1. lambda functions are also called anonymous functions, i.e., functions have no specific name. Let's start with a simple example:


def f(x):
return x**2
print f(4)

If you use lambda in Python, you write it like this


g = lambda x : x**2
print g(4)

2. lambda, compared with ordinary functions, is simply to omit the name of the function, while such anonymous functions cannot be shared and called elsewhere.

It's true that lambda doesn't make much of a difference in a dynamic language like Python, because there are plenty of alternatives.

When writing some execution scripts with Python, using lambda can save the process of defining functions and make the code more concise.

2. For functions that are abstract and cannot be reused elsewhere, it is sometimes difficult to give a name to a function. lambda does not need to worry about naming.

3. Using lambda sometimes makes the code easier to understand.

lambda basis

In THE lambda statement, the colon precedes the argument and can be multiple, separated by commas, with the return value to the right of the colon. The lambda statement actually builds 1 function object. Witness 1:


>>> foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
>>> print filter(lambda x: x % 3 == 0, foo)
[18, 9, 24, 12, 27]
>>> print map(lambda x: x * 2 + 10, foo)
[14, 46, 28, 54, 44, 58, 26, 34, 64]
>>> print reduce(lambda x, y: x + y, foo)
139

In terms of object traversal processing, actually Python's for.. in.. The if syntax is already strong and beats the lambda syntax in legibility.

defaultdict is a dictionary type and the default value can be set for defaultdict, which can be set via lambda.

Here are a few examples:


from collections import *             
x = defaultdict(lambda:0) // The default value is 0
print x[0]
y =defaultdict(lambda:defaultdict(lambda:0))// The default value is 1 The default value of a dictionary is 0
print y[0]
z = defaultdict(lambda:[0,0,0])// The default value is 1 A list, [0,0,0].
print z[0]

Output results:


0
defaultdict(<function <lambda> at0x7f097797af50>, {})
[0, 0, 0]

conclusion


Related articles: