Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use the Lambda function in Python

Shulou Source: shulou.com Published: 2022-06-01 22:45:53 10月18日 Update

This article mainly introduces the relevant knowledge of how to use the Lambda function in Python, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value, I believe you will have something to gain after reading this article on how to use the Lambda function in Python. Let's take a look.

What is Lambda?

Lambda function, also known as anonymous function. The lambda function is a small anonymous function. It can accept any number of parameters, but there can only be one expression.

Syntax lambda arguments: expression

Execute the expression and return the result:

Example

Add 10 to parameter an and return the result:

X = lambda a: a + 10print (x (5))

The best part of the Lambda function is that it is not limited to a single parameter. Instead, it can take as many parameters as needed. For example, in the following shared code snippet, it summarizes the parameters a, b, and c and returns the result:

X = lambda a, b, c: a + b + cprint (x (5,6,2)) Why to use the Lambda function

You can better demonstrate the power of lambda when you use them as anonymous functions in another function.

Suppose you have a function definition that takes an argument and that parameter will be multiplied by an unknown number:

Def myfunc (n): return lambda a: a * n

Use this function definition to create a function that always doubles the number you send:

Def myfunc (n): return lambda a: a * nmydoubler = myfunc (2) print (mydoubler (11))

Or, use the same function definition to create multiple functions in the same program: def myfunc (n):

Def myfunc (n): return lambda a: a * nmydoubler = myfunc (2) mytripler = myfunc (3) print (mydoubler (11)) print (mytripler (11)) this article on "how to use Lambda functions in Python" ends here. Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to use the Lambda function in Python". If you want to learn more, you are welcome to follow the industry information channel.

Tags: Function parameter knowledge result content article expression same code value single alias multiple power as far as possible simple operation number quantity article easy to understand Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Shulou Technology NVidia macOS Docker