Lambda
1 min readMay 15, 2023
- A lambda function is a small anonymous function.
- A lambda function can take any number of arguments, but can only have one expression.
- Use lambda functions when an anonymous function is required for a short period of time.
- filter(), map() are two built-in functions that receive lambda functions as arguments.
Map():
- The map function iterates all the lists (or dictionaries etc.) and calls the lambda function for each of their element.
- The output of map() is a list which contains the result returned by the lambda function for each item it gets called.
Filter():
- The filter function iterates the list and calls the lambda function for each element.
- It returns a final list containing items for which the lambda function evaluates to True.
Reduce():
from functools import reduce
- The reduce method continuously applies a function on an iterable (such as a list) until there are no items left in the list. It produces a non-iterable result, i.e., returns a single value.
examples:
- def fn(m, n) : return m + n
print(reduce((lambda m, n: m + n), [1, 2, 3, 4]))
print(reduce(fn, [1, 2, 3, 4])) - a = [1, 2, 3]
x = list(map(lambda y: y + 1, a))
print(x)
o/p = [2, 3, 4] - a = [1, 2, 3]
b = [2, 3, 4]
x = list(map(lambda a,b: a * b, a,b))
print(x)
o/p = [2, 6, 12] - def lam(n):
x = lambda a: a * n
return x
obj = lam(3)
print(obj(2))
o/p = 6
Reference: