Lambda functions are single-line functions that can take multiple arguments but have a single expression and return value.
There are three main components of the lambda function:
lambda
lambda arguments: expression
Add 20
to an argument (a
) and return the results:
x = lambda a:a+20print(x(5))
Lambda functions can take any number of arguments:
Multiply argument x
with argument y
and return the result:
s = lambda x, y : x * yprint(s(3, 4))
Add the argument a
,b
, and c
and return the result:
x = lambda a, b, c : a + b + cprint(x(3, 7, 9))
The lambda function is commonly used with the Python built-in functions filter()
and map()
.
filter()
The Python built-in filter()
function accepts a function and a list as an argument. It provides an effective way to filter out all the elements of the sequence and returns the new sequence whose function evaluates to True.
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]lst1 = list(filter(lambda x:(x % 2 == 0), lst))print(lst1)
map()
The map()
function in Python accepts a function and a list. It gives a new list that contains all modified items returned by the function for each item.
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]lst1 = list(map(lambda x:x * 2, lst))print(lst1)