Use of Lambda Function in Python
Let’s see some of the practical uses of the Python lambda function.
Condition Checking Using Python lambda function
Here, the ‘format_numric’ calls the lambda function, and the num is passed as a parameter to perform operations.
Python3
format_numeric = lambda num: f "{num:e}" if isinstance (num, int ) else f "{num:,.2f}" print ( "Int formatting:" , format_numeric( 1000000 )) print ( "float formatting:" , format_numeric( 999999.789541235 )) |
Output:
Int formatting: 1.000000e+06
float formatting: 999,999.79
Difference Between Lambda functions and def defined function
The code defines a cube function using both the ‘def'
keyword and a lambda function. It calculates the cube of a given number (5 in this case) using both approaches and prints the results. The output is 125 for both the ‘def'
and lambda functions, demonstrating that they achieve the same cube calculation.
Python3
def cube(y): return y * y * y lambda_cube = lambda y: y * y * y print ( "Using function defined with `def` keyword, cube:" , cube( 5 )) print ( "Using lambda function, cube:" , lambda_cube( 5 )) |
Output:
Using function defined with `def` keyword, cube: 125
Using lambda function, cube: 125
As we can see in the above example, both the cube() function and lambda_cube() function behave the same and as intended. Let’s analyze the above example a bit more:
With lambda function |
Without lambda function |
---|---|
Supports single-line sometimes statements that return some value. | Supports any number of lines inside a function block |
Good for performing short operations/data manipulations. | Good for any cases that require multiple lines of code. |
Using the lambda function can sometime reduce the readability of code. | We can use comments and function descriptions for easy readability. |
Python Lambda Functions
Python Lambda Functions are anonymous functions means that the function is without a name. As we already know the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python.
Contact Us