Lambda: Anomymous Functions
Definition
Lambda functions are defined by lambda keyword, which could only have one expression but multiple arguments. We can assign the lambda function to any variable so that we can use it as a function. More generally, we use lambda together with map, reduce or filter.
1 | ''' |
Usage
In addition to the basic usage above, there are 4 ways to make use of lambda in general.
Functions nested lambda
1 | def new_func(x): |
Anomymous functions are also functions and they have their own scope, because of which, anomymous function will use variables of enclosing function or global variables once they can't find the specific variable in the local scope.
map and lambda
map funtion makes use the idea of SIMD. It maps a certain function to all the elements of input list and return a iterator which can be turned to list using list().
1 | ''' |
map can also deal with two or more lists as long as the length of lists is the same and the function supports more than one arguments:
1 | for i in map(lambda x, y : x + y, [1, 2, 3], [4, 5, 6]): |
What's more, the element of list could even be function:
1 | def sq(x): |
reduce and lambda
reduce firstly passes the first two elements of list to the function. Then, take the result of function as the new first argument and pass it to the function with the third element of list and so on until the last element:
1 | ''' |
The element of list could also be function.
filter and lambda
filter returns a iterator that contains elements in the input_list that match the criteria of the function:
1 | ''' |
filteris easily replaced byfororfor ifcomprehension:
1 | a = [i for i in range(10)] |