Lambda function:
- A lambda function is an anonymous function (a function without a name).
- Define using the ‘lambda‘ keyword.
- Lambda functions can have any number of arguments.
- A lambda function is limited to a single expression.
- It is often used for a short period of time & simple operations.
Syntax:
1 | lambda arguments: expression |
- arguments: Input parameters.
- expression: The operation to be performed, which will be returned as the output.
Uses of Lambda Functions:
- Short Anonymous Functions: Lambda functions are useful when you need a small function for a short period of time and don’t want to define a full function using ‘def’.
- Functional Programming: Commonly used with functions like ‘map()’, ‘filter()’, and ‘reduce()’ to apply a function to an iterable.
- Sorting: Often used with sorting functions to provide custom sort keys.
- Inline Operations: Ideal for operations that are small and won’t be reused elsewhere.
Examples:
1 2 3 4 5 | # A lambda function to multiply by 100 Multiplyby100 = lambda x: x * 100 Multiplyby100( 35 ) |
Output: 3500
1 2 3 4 5 | # Using Mapping function with above lambda function my_list = [ 20 , 30 , 40 , 50 , 100 ] list ( map (Multiplyby100,my_list)) |
Output: [2000, 3000, 4000, 5000, 10000]
1 2 3 4 5 6 7 | #Using filter function with lambda my_list = [ 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 ] even = lambda x : x % 2 = = 0 list ( filter (even,my_list)) |
Output: [6, 8, 10, 12, 14]