A lambda function is essentially an anonymous or unnamed function. In the previous function section, we saw that the def
keyword is used to define a function. However, lambda functions do not require this.
Let’s see an example:
# This program is an example of lambda function in python
lam=lambda x: x*x # lambda function for single variable
lam2=lambda x,y: x*y
print(lam(5)) # single argument function call
print(lam2(5,10)) # double argument function call
Output:
25
50
In lines 3 and 5, a lambda function is defined for one and two arguments respectively. This function is assigned to a variable, and this variable acts as the name of the function.
Noteworthy points:
- A lambda function can have only one statement.
- A lambda function can accept any number of arguments.