Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Hello everyone, I am a bowl week, a front end that does not want to be drunk (inrolled). If I am lucky enough to write an article that you like, I am very lucky

Anonymous functions

In Python, in addition to the usual functions defined using DEF, there is another anonymous function defined using lambda. Such functions can be used anywhere normal functions can be used, but are strictly restricted to a single expression when defined. Semantically, it is just syntactic sugar for ordinary functions.

If we need to define a particularly simple function, for example

def add(a, b):
    s = a + b
    return s
Copy the code

This begs the question, how can such elegant Python produce such ugly code, and is there a way to reduce it to one line? There must be a way to simplify such elegant Python! This is where anonymous functions come in.

Python uses the **lambda** keyword to create anonymous functions.

Syntax format

Lambda [argument 1 [, argument 2,.. argument n]]: expressionCopy the code

Lambda argument list: return [expression] variable

Since lambda returns a function object (building a function object), you need to define a variable to receive it

Example code is as follows:

News_add = lambda a, b: a + b # = def news_add_old(a, b): Return a + b x = news_add_old(5, 10) y = news_add(5, 10Copy the code

Used in conjunction with built-in functions

list1 = [{"a": 10, "b": 20}, {"a": 20, "b": 20}, {"a": 50, "b": 20}, {"a": 6, "b": 20}, {"a": 9, "b": Print (max_value) def func(di) = Max (list1, key=lambda x: x["a"]) print(max_value) Return di["a"] max_value = Max (list1, key=func) # print(max_value)Copy the code

Take anonymous functions as arguments

def func(a, b, fun):
    s = fun(a, b)
    return s

z = func(5, 10, lambda a, b: a + b)
print(z)  # 15
Copy the code

Lambda can eliminate the need to define functions, make code more concise, and avoid naming problems, but it is not recommended in PEP8 specification.