What is lambda function?
Lambda function is single line function (also known as anonymous functions).
lambda keyword is used to create small anonymous functions.
lambdas are like normal functions and even behave like normal functions.
Syntax:
lambda arguments: manipulation statement(arguments)
Difference normal and lambda functions
- Lambda function can take many parameters but can return a single value which cannot return multiple expressions.
- An anonymous function cannot use a direct call to print because lambda requires an expression.
- Lambda functions cannot access variables other than those in their parameter list and those in the global namespace.
Python program for multiplication using lambda function.
#!/usr/bin/python
mul = lambda a, b: a * b
print("mul(2,4): %d" % mul(2, 4))
Output:
$ python lambda_test.py
mul(2,4): 8
How to use map function?
map function is used to apply the function to all the elements in the array or list.
map(function to apply, list)
Example:
#!/usr/bin/python
list_arr = [10, 20, 30, 40, 50]
updated_list = map(lambda x: x*2, list_arr)
print(updated_list)
Output:
$ python lambda_test1.py
[20, 40, 60, 80, 100]
How to use filter function?
filter function is used to filter the elements in the array based on lambda function return value is true.
filter(function_to filter, list)
Example:
#!/usr/bin/python
list_arr = [10, 20, 30, 40, 50]
updated_list = filter(lambda x: x>20, list_arr)
print(updated_list)
Output:
$ python lambda_test2.py
[30, 40, 50]
How to use reduce function?
reduce function is used to perform some computation on a list and returning the result.
Below python program is to compute sum of all elements in the list.
#!/usr/bin/python
from functools import reduce
list_arr = [10, 20, 30, 40, 50]
updated_list = reduce(lambda x,y: x+y, list_arr)
print(updated_list)
Output:
$ python lambda_test3.py
150
« Previous
Next »
Python Programming Language Examples