Lambda Functions

Python allows us to not declare the function in the standard manner, i.e., by using the def keyword. Rather, the anonymous functions are declared by using lambda keyword. However, Lambda functions can accept any number of arguments, but they can return only one value in the form of expression.

The anonymous function contains a small piece of code. It simulates inline functions of C and C++, but it is not exactly an inline function.

The syntax to define an Anonymous function is given below.

snippet
lambda arguments : expression

Example 1

snippet
x = lambda a:a+10 # a is an argument and a+10 is an expression which got evaluated and returned. 
print("sum = ",x(20))

Output:

Output
sum = 30

Example 2

Multiple arguments to Lambda function

snippet
x = lambda a,b:a+b # a and b are the arguments and a+b is the expression which gets evaluated and returned. 
print("sum = ",x(20,10))

Output:

Output
sum = 30

Why use lambda functions?

The main role of the lambda function is better described in the scenarios when we use them anonymously inside another function. In python, the lambda function can be used as an argument to the higher order functions as arguments. Lambda functions are also used in the scenario where we need a Consider the following example.

Example 1

snippet
#the function table(n) prints the table of n
def table(n):
    return lambda a:a*n; # a will contain the iteration variable i and a multiple of n is returned at each function call
n = int(input("Enter the number?"))
b = table(n) #the entered number is passed into the function table. b will contain a lambda function which is called again and again with the iteration variable i
for i in range(1,11):
    print(n,"X",i,"=",b(i)); #the lambda function b is called with the iteration variable i,

Output:

Output
Enter the number?10 10 X 1 = 10 10 X 2 = 20 10 X 3 = 30 10 X 4 = 40 10 X 5 = 50 10 X 6 = 60 10 X 7 = 70 10 X 8 = 80 10 X 9 = 90 10 X 10 = 100

Example 2

Use of lambda function with filter

snippet
#program to filter out the list which contains odd numbers
List = {1,2,3,4,10,123,22}
Oddlist = list(filter(lambda x:(x%3 == 0),List)) # the list contains all the items of the list for which the lambda function evaluates to true
print(Oddlist)

Output:

Output
[3, 123]

Example 3

Use of lambda function with map

snippet
#program to triple each number of the list using map
List = {1,2,3,4,10,123,22}
new_list = list(map(lambda x:x*3,List)) # this will return the triple of each item of the list and add it to new_list
print(new_list)

Output:

Output
[3, 6, 9, 12, 30, 66, 369]
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents