In Python, lambda or anonymous function means that a function is without a name. It is already known to us that a def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions. It has the following syntax:
lambda arguments: expression
The Following are the features of lambda. Remember lambda is a keyword in Python.
- This function (lambda) can have any number of arguments but only one expression, which is evaluated and returned.
- One can use lambda functions wherever function objects are required depending upon the requirement.
- You have to ensure that lambda functions are syntactically restricted to a single expression.
- It has various uses in particular fields of programming besides other types of expressions in functions.
The value of the expression associated with lambda will be returned at the end. This technique is used mainly when small coding is to be written within a function. Let us try to explain the usage of a lambda with some examples.
# Example of Lambda – To Find the Cube of a No
cube= lambda x: x*x*x
myno=int(input(“Enter The No”))
In the above, we have formed a lambda expression to find the cube of a no. Here x will be passed as a parameter and in the expression part, we are writing the formula for evaluating cube of x. Overall cube is called the lambda function.
This lambda function is being called when it is executing the following line –
print(cube(myno)) – where myno is the variable containing the value to be passed to x as a parameter. So if you enter 6 as the no. then your output will be 216.
So it is certain that lambda will always return a value. So if we want to do a comparison between a function and a lambda then perhaps the following table will help you to understand the major differences between a lambda & a function.
|1) We use a special keyword def to declare a function||1) We lambda Keyword to use a lambda expression.|
|2) We use the return keyword to return a value.||2) The value is automatically returned without the use of the return keyword.|
|3) A function can contain a block of statements||3) A lambda can contain only a single expression.|
|4) In Function, we can use the default parameter||4) Here there is no concept of default parameter.|
|5) A function may not return any value.||5) But in Lambda it is certain it will return a value.|