How to use lambda function in python

小老鼠
Release: 2023-12-13 16:29:40
Original
1004 people have browsed it

The lambda function in Python is an anonymous function, also called an inline function or function literal. Can be used to create simple, one-line functions, usually when a function is needed, but only used once, and does not need to be named. The basic syntax of a lambda function is "lambda arguments: expression".

How to use lambda function in python

The operating system for this tutorial: Windows 10 system, Python version 3.11.4, Dell G3 computer.

In Python, the lambda function is an anonymous function, also called an inline function or function literal. It can be used to create simple, one-line functions, usually when a function is required, but only used once, and does not need to be named.

The basic syntax of the lambda function is as follows:

lambda arguments: expression
Copy after login

Among them, arguments are the parameters of the function, which can be multiple parameters, separated by commas; expression is the return value of the function, usually an expression .

The following are some example usages of lambda functions:

# 一个参数的 lambda 函数
square = lambda x: x**2
print(square(5))  # 输出 25
# 多个参数的 lambda 函数
add = lambda a, b: a + b
print(add(3, 4))  # 输出 7
# 在列表排序中使用 lambda 函数
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
print(pairs)  # 输出 [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
Copy after login

In the above examples, the lambda function is used to define simple functions and can be used directly without using the def keyword to define the function . Lambda functions are typically used in functional programming, passed as arguments inside functions, or wherever a simple function is required.

It should be noted that lambda functions are usually used to write simple, single-line functions. If the function is more complex, it is recommended to use an ordinary def function to define it.

The above is the detailed content of How to use lambda function in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!