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.
y = lambda x : x + 1 print(y(1))
# Result: 2
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
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.
(Paris – Source: Wallpapers Wide ) </figcaption>
Syntax and usage
The syntax of the lambda function is as follows:
lambda arguments: expression
- 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
y = lambda x : x * 2
# Result: 20
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
Example 2: Lambda function with many arguments
ben = lambda x, y : x + y
# Result: 15
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
iter1 = [1, 5, 7]
iter2 = [9, 5, 3]
result = map(lambda x, y: x + y, iter1, iter2)
# Result: [10, 10, 10]
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
data_list = range(-5, 5)
# data_list = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
greater_than_zero = list(filter(lambda x: x > 0, data_list))
# Result: [1, 2, 3, 4, 5]
See more about Python Filter Function .