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