English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn about anonymous functions, also known as lambda functions. Through examples, you will understand what they are, their syntax, and how to use them.
In Python, anonymous functions are functions without a defined nameFunction.
Although 'def' uses the keyword to define a normal function in Python, anonymous functions lambda are defined using the keyword.
Therefore, anonymous functions are also called lambda functions.
The syntax of lambda functions in Python is as follows.
lambda arguments: expression
Lambda functions can have any number of arguments, but can only have one expression. The expression is evaluated and returned. Lambda functions can be used anywhere a function object is needed.
这是一个使输入值翻倍的lambda函数示例。
# 程序展示lambda函数的使用 is the expression for evaluation and return. * 2 This is an example of a lambda function that doubles the input value.5# The program demonstrates the use of lambda functions
Output result
10
print(double( * 2)) * 2In the above program, lambda x: x
is a lambda function. Here x is the parameter, x
is the expression for evaluation and return. * 2
This function has no name. It returns a function object, which is assigned to the identifier double. Now we can call it a normal function. Below is the declaration
double = lambda x: x equivalent to: * 2
return x
Using Lambda functions in pythonwhen we temporarily need an anonymous function, we use lambda functions.In Python, we usually use it as a parameter of higher-order functions (functions that take other functions as
Lambda functions can be used with filter(), map(), and other built-in functions.
Example of using lambda with filter()
The filter() function in Python takes a function and a list as parameters.
This is an example of using the filter() function to filter out only even numbers from the list. my_list = [1, 5, 4, 6, 8, 11, 3, 12] # The program filters out even numbers from the list2 new_list = list(filter(lambda x: (x% print(new_list)
Output result
[4, 6, 8, 12]
Example of using lambda with map()
The map() function in Python takes a function and a list.
This is an example of using the map() function to double all items in the list.
# Use map() to double each item in the list my_list = [1, 5, 4, 6, 8, 11, 3, 12] new_list = list(map(lambda x: x * 2 , my_list)) print(new_list)
Output result
[2, 10, 8, 12, 16, 22, 6, 24]