Lambda Expression
In Python, A lambda function is a small anonymous function. Anonymous function means that a function is without a name. As we already know that def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions. It has the following syntax:
lambda arguments : expression
x = lambda a, b : a * b
print(x(5, 6))
# 30
y = lambda a : a + 10
print(y(5))
# 15
>>> type(x), type(y)
<class 'function'>
Although the type of lambda is a function, you can assign it to an identifier like : f = lambda a: a+10 This is strongly discouraged, mainly where functions should be used and have more benefits.
Using lambda expressions for map, filter and reduce
Lambdas are very commonly used with map() and filter() as shown.
nums = [0, 1, 2, 3, 4, 5]
mapped = map(lambda x: x * x, nums)
filtered = filter(lambda x: x % 2, nums)
print(list(mapped))
# [0, 1, 4, 9, 16, 25]
print(list(filtered))
# [0, 2, 4]
map functions expect a function object and any number of iterables, such as list, dictionary, etc. It executes the function_object for each element in the sequence and returns a list of the elements modified by the function object.
Thefilterfunction expects two arguments: function_object and an iterable. function_object returns a boolean value and is called for each element of the iterable. Filter returns only those elements for which the function_object returns true.
map(func, *iterables) --> map object filter(function or None, iterable) --> filter object
Note that map and filter return map/filter object so we need to cast to list to get the result.
Filter list of dicts:
dict_a = [{'name': 'python', 'points': 10}, {'name': 'java', 'points': 8}]
filter(lambda x : x['name'] == 'python', dict_a)
# [{'name': 'python', 'points': 10}]
Reduce is a really useful function for performing some computation on a list and returning the result. It applies a rolling computation to sequential pairs of values in a list. For example, if you wanted to compute the product of a list of integers.
So the normal way you might go about doing this task in python is using a basic for loop:
product = 1
list = [1, 2, 3, 4]
for num in list:
product = product * num
# product = 24
Now let’s try it with reduce:
from functools import reduce
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
# Output: 24