Lambdas
Code sample link: https://replit.com/@jjoco/python-lambdas
Lambda functions can be thought of short-term, concise, impromptu functions that are intended to be thrown away after one or a couple of uses.
Why use lambda functions
Lambdas are commonly used in other functions that have functions as parameters (ie higher-order functions).
Creating a standalone-lambda function
You can create lambda functions to implement very concise one-line functions. Use the keyword lambda
to create a function.
Syntax:
1 |
|
Let's go over a more concrete example:
1 2 3 4 5 |
|
double_funct
and add_funct
. These lambda functions are used like any other function. In this example, we're using lambda
to implement very short functions, whose scope is narrowed to the current code block.
Creating a lambda generator function
What is cool is that we can create a lambda generator, which we can use to easily create more lambda functions on demand:
1 2 3 4 5 6 7 8 |
|
exp_funct
to generate lambda functions that raise an input to the n-th power.
Using lambda functions as inputs to other functions
Lambda functions are commonly used as inputs to functions, whose required (or optional) parameters are also functions.
Take the following example:
1 2 3 4 5 6 7 8 |
|
sorted
to define how to sort the key values pairs in card_map
. Specifically, we're sorting key-value pairs in card_map
by the values. Then we're taking the list of 2-tuples in sorted_list
and turning it into a dictionary.