A lambda function in Python is an anonymous function that can take any number of arguments but can return only one expression. A lambda function is defined by using the ‘lambda’ keyword.
Syntax
lambda arguments: expression
In the syntax:
arguments are any value passed
expression is the returned value
Example:
addition = lambda x, y : (x + y)
print(addition(4,7))
Output:
11
In the above example, the lambda function is represented by lambda x, y : (x + y). X, y are the arguments and (x+y) is the returned value. It produces a function object which is then stored in the variable ‘addition’. So ‘addition’ can be further used as a standard Python function.
Using if – else with lambda functions
We can also put conditional statements if – else to return a result based on certain condition in lambda functions. Consider this example.
findMaximum = lambda x,y : x if(x > y) else y
print(findMaximum(1,4))
Output:
4
Uses of lambda functions
- A lambda function can be used inline, so when there is not too much complex logic, you don’t need to define a regular function.
- A regular function can be defined once and used multiple times. On the other hand a lambda function works best when the logic is to be applied only once.
Pros
- It’s syntax is much simpler than a regular function.
- It’s an ideal choice for performing an operation that is to be done only once.
Cons
- It can’t have any variable assignment. For example lambda x : x = 1 will throw an error.
- It cannot perform multiple operations.