Python Lambda Function (Translate)

Tram Ho

The article is translated from the original Python Lambda Function of Python Geeks

The Lambda function is an anonymous function. Meaning no function name as usual. In this article, the author presents the syntax and usage of lambda functions through specific examples. Hopefully after viewing this article, you will be able to use it in your code.

Quick example:

What is Lambda Function?

In Python, an anonymous function is a function without a name. A normal function will start with the keyword def . However, the anonymous function begins with the keyword lambda . That is why they are often called lambda functions.

Usually the Python lambda function will be used by you who have a lot of experience with Python. So, knowing and using lambda functions well in addition to making the code more beautiful and concise, it also helps to show your experience and level.

How Python Lambda Function make your beautiful code <figcaption>
(Paris – Source: Wallpapers Wide ) </figcaption>

Syntax and usage

The syntax of the lambda function is as follows:

  • arguments: Can use multiple arguments at the same time.
  • expression: But there is only one expression. Expression will be executed and the result returned.

Examples of Python Lambda

Example 1: Lambda function with only 1 argument

In the above example, lambda x : x * 2 is an anonymous function. x is the only argument. x * 2 is the expression to be executed. When we assign x = 10 , the expression will execute and return 20 .

Example 2: Lambda function with many arguments

In the above example, we defined a lambda function with 2 arguments. If you want to be able to add more arguments. However remember that there is only one expression.

Example 3: Lambda And Map Function

In Python, we often use lambda as argument of higher-order functions like filter (), map (). You can see more article about Python Map Function

Example 4: Lambda And Filter Function

See more about Python Filter Function .

Share the news now

Source : Viblo