A lambda function is an anonymous function. In this post, we'll learn what is it, its syntax and how to use it (with examples). After that, we can make our code better by using lambda.
A Quick Example:
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 by def
keyword. An anonymous function defines by the lambda
keyword, therefore we usually call them as a lambda
function.
Python lambda function is frequently used by the senior level of developers. So we should understand it and use effectively in our coding. We will be surprised because of our beautiful code with lambda.
Definition And Usage
In python, a lambda syntax as below:
lambda arguments: expression
- arguments: Can pass many arguments.
- expression: But only one expression. The expression is executed and the result is returned.
Python Lambda Examples
Example 1: Lambda function with only 1 argument
y = lambda x : x * 2
print(y(10))
# Result: 20
In this example, lambda x : x * 2
is an anonymous function. x
is the only argument. x * 2
is the expression that will be executed and returned. When we x = 10
, the expression executed, after that we get 20
as a result.
Example 2: Lambda function with multiple arguments
ben = lambda x, y : x + y
print(ben(5, 10))
# Result: 15
In above example, we defined lambda
function with 2 arguments. We can have as many arguments as we want. 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)
print(list(result))
# Result: [10, 10, 10]
In Python, we generally use lambda as an argument of higher-order function such as filter(), map(). If you are new to Python, try reading our articles (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))
print(greater_than_zero)
# Result: [1, 2, 3, 4, 5]
Read the following article for understanding the filter function in Python (Python Filter Function).
The post Python Lambda Function appeared first on Python Geeks.
Top comments (0)