English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Knowledge of Python

Python Reference Manual

Python Anonymous Functions (Lambda)

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.

What is the lambda function in Python?

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.

How to use lambda functions in Python?

The syntax of lambda functions in Python is as follows.

Syntax of Lambda function in Python

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 function example in Python

这是一个使输入值翻倍的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

def double(x):

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

arguments

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]

== 0) , my_list))

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]