Lambda expressions¶
What is a lambda expression?¶
The lambda expression is otherwise an anonymous function. It is a function that has no name and is defined where it is used. It is not defined by the keyword def.
The keyword lambda is used, followed by a comma-separated list of arguments, followed by a colon, followed by a single expression that returns the value of the function.
Examples¶
1.
my_lambda = lambda x: x.lower()
my_lambda("HA HA HA") # "ha ha ha"
In the above example, we create a function called my_lambda that takes one argument, which is a string, and returns it as all letters have been converted to lowercase. It is a simplified notation of a function defined as follows:
def my_lambda(x):
return x.lower()
We call the anonymous function as we know it: we give its name, and pass its arguments in round brackets.
2.
square_lambda = lambda x: x ** 2
square_lambda(4) # 16
Here we create a function called square_lambda that returns the square value of the argument passed to it.
3.
equals_lambda = lambda x, y: x == y
equals_lambda(1, 2) # False
Here is an example of an anonymous function that takes two arguments and returns a logical value as to whether their values are equal.
Application¶
We must bear in mind that the use of lambda expressions may affect the readability of the code. We can meet with their use where there is no need to create functions, but only want to provide information on how the data is to be transformed.
map, reduce, filter¶
Most often, these expressions are used in functions map, reduce and filter.
- function map
items = [1, 2, 3, 4, 5] squared = list(map(lambda x: x ** 2, items)) # [1, 4, 9, 16, 25]
The map function transforms (maps) the values of a collection as described by the function.
In this example, each item in the items list is squared and saved in the squared list.
- function filter
odds = list(filter(lambda x: x % 2, items)) # [1, 3, 5]
The filter function will remove (filter) those collection items for which the function returns False. In other words, after filtering, the list will be left with those elements for which the function value was True.
In this example, all items in the items list are split modulo 2 and those for which the result was greater than zero (0 is False, any greater than zero True) will be saved in the odds list.
- function reduce
from functools import reduce items_sum = reduce(lambda x, y: x + y, items) # 15
The reduce function processes the elements of a collection from left to right as described in the lambda expression, and produces a single value. So you can say that the collection is reduced to a single value. In the first step, the function operates on the first two elements of the collection and returns the result of transformation, then it is rerun: for the result achieved in the previous step and the next value from the list. The process continues as long as there are still items in the list.
In this example, we first operate on the numbers 1 and 2, add them together to get 3. Then we add this result to the next item in the list, which is 3, obtaining 6. Then, we add another item of the list to the result, which is 4, and we get 10. In the last step, we add the last element of the list to 10, which is 5, resulting in 15. So the whole list is mathematically processed as follows:
(((1 + 2) + 3) + 4) + 5 = 15
sorted, max, min¶
We have already learned about the built-in sorted, min and max functions. We didn't mention, however, that all of them take an optional argument called key, with which we can define by what criteria we would like to sort the collection or select the largest and smallest element.
- function sorted
pairs = [(1, 10), (2, 9), (3, 8)]
For example, we would like to be able to sort the list of records by the values in the second position. To do this, we can pass a lambda expression in the key parameter that will transform the elements of the collection in the appropriate way.
sorted(pairs, key=lambda x: x[1]) # [(3, 8), (2, 9), (1, 10)]
By default, the list of records would be sorted on the items in the first position. By passing a lambda expression in the key parameter, we can signal that we are interested in ordering the list items after the values appearing in second place in each tuple.
- functions min and max
It is similar with the functions min and max.
min(pairs) # (1, 10)
max(pairs, key=lambda x: x[1]) # (1, 10)
max(pairs, key=lambda x: x[0] * x[1]) # (3, 8)
By default, the highest and lowest value in the list will be searched for among the items appearing on the first position in each record. By passing an appropriate lambda expression in the key parameter, we can signal that we are considering only those record elements that appeared in the second position. We may also, as in the last example, want to return the record for which the product of its elements is the greatest.